'Use loop to clear. textBox[i].Clear(). Is this possible?

I am just looking to know this to try and clean up my code, and also for future reference.

I have a number of textBoxes.

        tbPart1.Clear();
        tbPart2.Clear();
        tbPart3.Clear();
        tbPart4.Clear();
        tbPart5.Clear();
        tbPart6.Clear();
        tbPart7.Clear();

Is there any way I could use a loop to replace the numbers?

I tried this, but have no idea how i could run the string.

        for (int i = 1; i == 7; i++)
        {
            string p = "tbPart" + i.ToString() + ".Clear";
        }


Solution 1:[1]

Inside of the form's code (i.e. in a button click event handler), you can enumerate through all of the TextBox controls on the form and perform a specific action on them:

this.Controls.OfType<TextBox>().ToList().ForEach(x => x.Clear());

If you need to only clear some of the TextBox controls, you can provide a sort of filter like so:

this.Controls.OfType<TextBox>()
    // Add a condition to clear only some of the text boxes - i.e. those named "tbPart..."
    .Where(x=>x.Name.StartsWith("tbPart"))
    .ToList().ForEach(x => x.Clear());

Solution 2:[2]

No, you cannot do it that way. But you can define an array or list where you put the controls and then clear them. For example:

List<TextBox> textboxes = new List<TextBox>();
textboxes.Add(tbPart1);
textboxes.Add(tbPart2);
textboxes.Add(tbPart3);
...

Then when you want to clear them

foreach (var tb in textboxes)
    tb.Clear();

Solution 3:[3]

TextBox[] boxes = new [] {
    tbPart1,
    tbPart2,
    tbPart3,
    tbPart4,
    tbPart5,
    tbPart6,
    tbPart7
};

for (int i = 0; i < boxes.Length; i++)
{
    boxes[i].Clear();
}

Solution 4:[4]

i think you should use an array of textbox then you can do a loop depends the count of numbers of textboxes.

Solution 5:[5]

foreach(Control ctrl in this.Controls)
{
    if(ctrl.GetType() == typeof(TextBox))
    {
        ctrl.Text = String.Empty;
    }
}

Solution 6:[6]

Answer number one by using Control name inside panel1

private void button2_Click(object sender, EventArgs e) { string currentCtrlName;

        for (int i = 0; i < panel1.Controls.Count; i++)
        {
            currentCtrlName = "textBox" + (i+1).ToString();
            panel1.Controls[currentCtrlName].Text = "";
        }

    }

================== Answer number one by using Control index as a child inside panel1

private void button2_Click(object sender, EventArgs e) {

        for (int i = 0; i < panel1.Controls.Count; i++)
        {
            panel1.Controls[i].Text = "";
        }

    }

==================

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael
Solution 2 Sami Kuhmonen
Solution 3 Dmytro Shevchenko
Solution 4 rondec june
Solution 5 deathx91
Solution 6 Mohammad Hashem