Tom Carroll Tom Carroll - 2 months ago 16
C# Question

Casting string + enum value to TextBox type

I currently have 14 text boxes on a form (there is going to be up to 30 when development is finished) stored in an array 'textBox'. Each text box represents a price a competitor is advertising a particular product on their website for. The name of each text box is prefixed with 'txt' and then the dealers name.

Throughout my code there is a lot of manipulation of textBox[i].Text, textBox[i].BackColor etc. As well as manipulation of the corresponding label ('lbl' + dealer name) and variables ('str' + dealer name).

What I would like to do is have an enum of dealer names, then on the form load assign the arrays to the have each item corresponding to an item in the enumeration.

Something like:

enum Dealers { DealerName1, DealerName2, DealerName3, DealerName4 etc..};
string[] prices = new string[13];
TextBox[] textBox = new TextBox[13];
Label[] labels = new Label[13];

for (int i = 0, i < 14, i++)
textBox[i] = txt + //Name of dealer at enum position i
label[i] = lbl + //Name of dealer at enum position i

//do processing and assign prices variables

for (int i = 0, i < 14, i++)
textBox[i].Text = prices[i]

My question is what is the correct syntax to concatenate "txt" and the dealer name in the enum at the relevant integer position and then use that to assign textBox[i]


You should use method FindControl("IDOfControl"). - this is for .net web forms

 for (int i = 0, i < 14, i++)
      textBox[i] = (TextBox)FindControl("txt" + (Dealers)i)
      label[i] = (Label)FindControl("lbl" + (Dealers)i)


If you are writing winforms you should use this.Controls.Find("IDOfYourControl", true)[0] instead FindControl("") method.