开发者

Change C# Variable Name Dynamically in Loop

开发者 https://www.devze.com 2023-02-16 18:35 出处:网络
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

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 l开发者_如何转开发ike 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;


do you want to change label name to accomplish which aim? do you have label named as: label1, label2, label3 and you'd like to change their text property?

you could do that by using linq.

0

精彩评论

暂无评论...
验证码 换一张
取 消