josap josap - 1 year ago 78
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

, ...,

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 Source

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...
// 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download