tags:

views:

321

answers:

4

I'm 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 of... etc of a object that just raised an event.

The above tends to break when the layout changes and the number of .Parents increase or decreases.

I don't necessarily have a control Id, so I can't use FindControl().

Is there a better way to find the 1st parent grid?

+9  A: 
Control parent = Parent;
while (!(parent is RadGrid))
{
    parent = parent.Parent;
}
Joel Lucsy
I like this one. I'll probably add an counter to throw an assertion/error if it goes into an infinite loop.
MatthewMartin
+1  A: 

I'm not familiar with the API that you are using, but can you do something like:

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;
Erich Mirabal
+1  A: 

If you have control of the Parent's code, you could use simple recursion to do it, I'd think. Something like:

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

I make no claims as to how well that will work, but it should get the idea across. Navigate up the parent chain as far as it goes until there is no parent, then return that object back up the recursion chain. It's brute force, but it will find the first parent no matter how high it is.

CodexArcanum
+3  A: 

If you really have to find the grid, then you might something like this:

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

But maybe you can explain why you need a reference to the grid? Maybe there is another/better solution for your problem.

M4N