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.

2
  • 3
    In general, whenever you have variables (or in this case controls) named item_0, item_1, ... item_N you should stop and ask yourself, "Can I use an array for this instead?" Commented Aug 25, 2013 at 22:26
  • And perhaps a different control, like a listbox, would be more appropriate. Commented Aug 25, 2013 at 22:35

3 Answers 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 = "";
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

5

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

Anyway try this this.Controls.Find()

Comments

1

You should be able to linq to it.

TextBox txtBox = this.Controls.Select( c => c.Name == cell );
txtBox.Text = "";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.