Home > OS >  how to find a control's location based on the control's name
how to find a control's location based on the control's name

Time:11-13

I want to basically find a control's location based on name. This is what I have so far:

private Point FindControlLocation(string ControlName, Control ParentControl)
{
    //Code...
}

Thanks for any help!

CodePudding user response:

Try this:

private Point FindControlLocation(string ControlName, Control ParentControl)
{
        return ParentControl.Controls[ControlName].Location;
}

And this is an example of how to use the function:

MessageBox.Show(FindControlLocation("Button1", this).ToString());

CodePudding user response:

You don't actually need the parent control, just use the Form and the recursive option from Controls.Find():

private Point FindControlLocation(string ControlName)
{
    Control ctl = this.Controls.Find(ControlName, true).FirstOrDefault() as Control;
    return (ctl != null) ? ctl.Location : new Point();
}
  • Related