4

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.

4

3 回答 3

8

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 = "";
        }
    }
}
于 2013-08-25T22:16:21.650 回答
5

I recommend you using of two-dimentional array of TextBoxes. This will make your life easier.

Anyway try this this.Controls.Find()

于 2013-08-25T22:15:58.270 回答
1

You should be able to linq to it.

TextBox txtBox = this.Controls.Select( c => c.Name == cell );
txtBox.Text = "";
于 2013-08-25T22:29:44.360 回答