DaveL
DaveL

Reputation: 87

Edit a button by its given name

I am generating x amount of buttons and I give all of them a unique name.

After all those are generated, I want to edit one of them without regenerating them so I was wondering if I could get a component by its name?

I am using WinForms

Upvotes: 1

Views: 95

Answers (4)

Max
Max

Reputation: 13338

After all those are generated, I want to edit one of them without regenerating them so I was wondering if I could get a component by its name?

var myButton = Controls.Find("buttonName", true).FirstOrDefault(); //Gets control by name
if(myButton != null)
{
    if (myButton.GetType() == typeof(Button)) //Check if selected control is of type Button
    {
       //Edit button here...
    }
    else
    {
       //Control isn't a button
    }
}
else
{
    //Control not found.
}

Make sure you add a reference to: linq.

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

You can use Controls property of your form (or some container control on your form). With LINQ you can select buttons and then find first button with required name:

var button1 = Controls.OfType<Button>().FirstOrDefault(b => b.Name == "button1");

Or if you want to search child controls recursively

 var button1 = Controls.Find("button1", true)
                       .OfType<Button>()
                       .FirstOrDefault();

Without LINQ you can use method Find(string key, bool searchAllChildren) of ControlCollection:

Control[] controls = Controls.Find("button1", true);
if (controls.Length > 0)
{
    Button button1 = controls[0] as Button;
}

Upvotes: 0

Sailesh Babu Doppalapudi
Sailesh Babu Doppalapudi

Reputation: 1544

Button btn1 = (Button)(Controls.Find("btnName"));

This will get the required button and will save the button attributes into a new Button btn1

Upvotes: 0

Adriano Carneiro
Adriano Carneiro

Reputation: 58595

Yes:

Control myControl = Controls.Find("textBox1");

Now, beware that you have to do proper casting hen found, because Find returns a control.

Upvotes: 2

Related Questions