Changing the C # variable name dynamically in a loop

advertisements

I am trying to enable and rename labels within a MySQLDataReader in C#. I am willing to do this outside of the loop if possible, but was wondering if there was a way to dynamically change the name of a variable. For example:

while (listNamesREAD.Read())
{
    int i = 0;
    //TextBox1.Text = TextBox1.Text + fieldnames.GetString(0) + ", ";
    stringArray[i] = "List #" + listNamesREAD.GetString(0) + ": " + listNamesREAD.GetString(1);
    list1Label.Text = stringArray[i];
    i++;
}

If possible I would like the code to be able to change the name of list1Label each time it loops through. I am relatively new to Visual C# so any help would be greatly appreciated.

using (MySqlCommand cmd0 = new MySqlCommand(listNames, conn))
{
    conn.Open();
    listNamesREAD = cmd0.ExecuteReader();
    try
    {
        while (listNamesREAD.Read())
        {
            int i = 0;
            //TextBox1.Text = TextBox1.Text + fieldnames.GetString(0) + ", ";
            stringArray[i] = "List #" + listNamesREAD.GetString(0) + ": " + listNamesREAD.GetString(1);
            list+i+Label.Text = stringArray[i];
            i++;
        }
    }

I am also willing to accomplish this outside of the DataReader if possible as well. Using a normal while loop because the array size is dynamic so I know exactly how many times to loop through -- it's just a matter of dynamically changing variable names.


You will need to have an array of TextBoxes you loop through. There is no way to accomplish this how you want to as C# is a statically typed language.

You can use the Controls property (which is a collection of all controls in the form) to accomplish what you need. You can access the controls by the indexer and the Controls' name:

  this.Controls["label1"].Text = yourText;