views:

48

answers:

3

Hi there, 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

+1  A: 

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?

chris.w.mclean
+3  A: 
Button button1 = (Button)this.Controls[controlName];
Binary Worrier
Thanks all three of you, I knew it was simple once you know how!
Nathan
+1  A: 

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";
shahkalpesh
This one ended up working more reliably in the end, and compiles fine for me, thanks :)
Nathan