Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a string to call a variable in C#

Tags:

string

c#

I am trying to use a loop to edit the data of multiple text boxes, but I cannot figure out how to convert a string of which the contents are the name of my box to access the text element of each box.

       private void reset_Click(object sender, EventArgs e)
    {
        string cell;
        for(int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 9; j++)
            {
                cell = "c" + Convert.ToChar(i) + Convert.ToChar(j);
                cell.text = "";
            }
    }

My text boxes are named "c00, c01, .... c87, c88" which is what the contents of my "cell" variable would be during each iteration, however the code above does not work because it is trying to access the "text" element of a string which obviously does not make sense.

Obviously I could clear the contents of each box individually but since I will have multiple events which will change the contents of the text boxes it would be ideal to be able to implement a loop to do so as opposed to having 81 lines for each event.

like image 348
beverts312 Avatar asked Dec 09 '22 13:12

beverts312


1 Answers

It's far better to use an array. Either a 2D array like this:

TextBox[,] textboxes = ...

private void reset_Click(object sender, EventArgs e)
{
    for(int i = 0; i < textboxes.GetLength(0); i++)
    {
        for (int j = 0; j < textboxes.GetLength(1); j++)
        {
            textboxes[i,j].Text = "";
        }
    }
}

Or a jagged array like this:

TextBox[][] textboxes = ...

private void reset_Click(object sender, EventArgs e)
{
    for(int i = 0; i < textboxes.Length; i++)
    {
        for (int j = 0; j < textboxes[i].Length; j++)
        {
            textboxes[i][j].Text = "";
        }
    }
}
like image 135
p.s.w.g Avatar answered Dec 20 '22 08:12

p.s.w.g