3

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?

3
  • Recursion is your friend in this type of problem. Commented Apr 20, 2009 at 23:11
  • 1
    Recursion is sometimes a solution, but never your friend ;-) Commented Apr 20, 2009 at 23:25
  • While recursion is a natural solution for some problems it has limitations. The biggest are stack overflow ;-) and function call overhead. Commented Apr 21, 2009 at 0:22

4 Answers 4

13
Control parent = Parent;
while (!(parent is RadGrid))
{
    parent = parent.Parent;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I like this one. I'll probably add an counter to throw an assertion/error if it goes into an infinite loop.
3

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.

Comments

1

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;

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.