Nath
Nath

Reputation: 203

get the control with a certain name provided as a string in c#

i have the name of a control in a string and I want to manipulate the control, how do i turn the string into the current form instance of that control in c#?

e.g.

string controlName = "Button1";

What goes here?

button1.text = "Changed";

Thanks

Upvotes: 2

Views: 209

Answers (3)

Binary Worrier
Binary Worrier

Reputation: 51711

Button button1 = (Button)this.Controls[controlName];

Upvotes: 3

shahkalpesh
shahkalpesh

Reputation: 33476

Inside the form, you could write (c#)

this.Controls["Button1"].Text = "Changed";

I suppose, this could be the syntax in vb.net

Me.Controls("Button1").Text = "Changed"

EDIT: I don't know, if that would compile. @Binary Worrier is right

Button btn1 = this.Controls["Button1"] as Button;
btn1.Text = "Changed";

Upvotes: 1

chris.w.mclean
chris.w.mclean

Reputation: 1821

You need to look up the control in the controls collections, then cast it to the correct type. Is this in WPF , WinForms or ASP.Net?

Upvotes: 1

Related Questions