0

Let's say I have multiple TextBoxs and I want to concatenate numbers like this. Then, I want to add some text on it. Is this possible to do somehow? This is what I have so far:

for (int i = 0; i<5; i++)
{
    string str = "Textbox" + i.ToString();
    str.Text = "testing";
}

I am not sure how to do this. Can someone point me in the right direction, please?

David Duran
  • 1,720
  • 1
  • 27
  • 36
kunz
  • 895
  • 1
  • 7
  • 26
  • Write down an example, your question is not clear. – jAC Jul 23 '17 at 10:18
  • 1
    You can find control by its name. https://stackoverflow.com/questions/14510065/how-to-find-a-text-box-by-name-and-write-its-contents-to-a-text-file – lkdhruw Jul 23 '17 at 10:20

2 Answers2

0

Maybe try to use the Interpolated Strings

An interpolated string looks like a template string that contains interpolated expressions. An interpolated string returns a string that replaces the interpolated expressions that it contains with their string representations.

Example:

for (int i = 0; i<5; i++)
{
    str = $"Textbox{i}";
    str.Text = "testing";
}
Linus Juhlin
  • 975
  • 9
  • 30
pushStack
  • 1,777
  • 1
  • 11
  • 14
0

Well, Here is another method that you can use, you will have to keep track of all the text boxes in your form and add them to a global list.

Dictionary<string,TextBox> texts = new Dictionary<string,TextBox>();

On your FormLoad do this

foreach (Control c in this.Controls)
    if (c.GetType() == typeof(TextBox))
       texts.Add(c.Name,(TextBox)c);

and whenever you want to get any textbox, do this

 TextBox targetBox;
 texts.TryGetValue("textBox1", out targetBox);

Your for loop will look like

for (int i = 0; i<5; i++)
{
    string str = "Textbox" + i.ToString();
    TextBox targetBox;
    texts.TryGetValue(str, out targetBox);
    targetBox.Text = "testing";
}

An advantage to this approach is your entire textbox(any control for that matter) collection is in a dictionary so you can look-it-up even if the text boxes do not follow a generic naming scheme.

Suraj S
  • 979
  • 6
  • 18