How can I avoid .Parent.Parent.Parent. etc. when referring to management hierarchies?

I am trying to fix this ugly code.

RadGrid gv = (RadGrid) (((Control) e.CommandSource).Parent.Parent.Parent.Parent.Parent);

I often need to find the first grid that is the parent of the parent element ... etc. the object that just raised the event.

The above tends to break when you change the layout and increase or decrease the number of .Parents.

I do not have a control identifier, so I cannot use FindControl ().

Is there a better way to find the first parent grid?

+3
source share
4 answers
Control parent = Parent;
while (!(parent is RadGrid))
{
    parent = parent.Parent;
}
+12
source

If you really need to find a grid, you can do something like this:

Control ct = (Control)e.CommandSource;
while (!(ct is RadGrid)) ct = ct.Parent;
RadGrid gv = (RadGrid)ct;

, , , ? , / .

+3

API, , - :

Control root = ((Control)e.CommandSource);
while(root.Parent != null)
{
    // must start with the parent
    root = root.Parent;

    if (root is RadGrid)
    {
        // stop at the first grid parent
        break;
    }
}
// might throw exception if there was no parent that was a RadGrid
RadGrid gv = (RadGrid)root;
+1

, , , . - :

public Control GetAncestor(Control c)
{
    Control parent;
    if (parent = c.Parent) != null)
        return GetAncestor(parent);
    else 
        return c;   
}

, , . , , . , , , .

+1

Source: https://habr.com/ru/post/1706760/


All Articles