josap josap - 23 days ago 8
C# Question

Variable IDs in C#

When programming a Windows Forms application I found myself having to create a variable amount of text fields according to the number of inputs.

I decided to name these

name1
,
name2
,
name3
, ...,
nameN
.

Now I want to be able to save the user's input to a text file. To do this I need to get the text from the text boxes into separate variables to be able to write this to the text file.

This would result in a for loop like this:

for(i=0; i < totalnames; i++)
{
string varname= "name" + i;
}


But this way I cannot get the value from the text boxes. How can I get the separate values from the text boxes to write them to the text file?

Thank you,

Answer

When you create the form controls, keep references to them in a list:

// probably at the class level...
List<TextBox> myTextBoxes = new List<TextBox>();

// then when you create them...
myTextBoxes.Add(name1);
// etc.

Then later, when you need to reference them, use the list:

foreach (var textBox in myTextBoxes)
{
    // get the value from the text box and use it in your output
}