0

Possible Duplicate:
C# Get control by name

I have been looking around for an answer for this now for a while and was wondering if someone would help me please.

I would like to convert a type String into type TextBox so say below.

String text = "textBox" + number;

TextBox tb = text;

I would like to do this so I receive the number and then I know which textBox to write to.

Any help would be most appreciated! :)

Community
  • 1
  • 1
James
  • 474
  • 4
  • 9
  • 22

3 Answers3

3
String text = "textBox" + number;
TextBox tv = (TextBox)FindControl(text);
j_mcnally
  • 6,928
  • 2
  • 31
  • 46
  • 1
    I have just been looking to find how you use "FindControl" could you explain it as I have never come across it before and I can't find a good example? Thank you for the help as well! – James Feb 19 '12 at 21:22
3

Well, you could get the variable using reflection, but what I think that you really want to is to just find the actual control.

Use the FindControl method to get a reference to the actual textbox:

TextBox tb = FindControl("textBox" + number.ToString()) as TextBox;
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • I got the error with HTML controls. It is successfully run with asp.net controls. – Sagar Jul 11 '14 at 16:09
  • @Viktor: An HTML tag needs to have `runat="server"` to be a server control, otherwise it's just treated as text on the server side. – Guffa Jul 13 '14 at 11:46
0

Do you have an array of text boxes? Is that windows form / web?

Basically what you can to is find to go through the Controls collection of the container and find an element with the the ID.

Note that my answer is pretty wide and not accurate on all cases. If you'll provide more details I'll help you further.

nadavy
  • 1,755
  • 1
  • 18
  • 33