Increase the number in the textbox name
public void test()
{
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
for (int i = 1; i <= list.Count; i++)
{
textBx.Text = list[i].ToString();
// I want it to be textBx1.Text = list[1].ToString();
textBx2.Text = list[2].ToString();
textBx3.Text = list[3].Tostring();
etc.
// I can't create textbox dynamically as I need the text box to be placed in specific places in the form . How do I do it the best way?
}
}
0
source to share
2 answers
Sounds like a job for Controls.Find (). You can build your string dynamically and search for a TextBox with this name:
var textBox = this.Controls.Find("textBx" + i, true) as TextBox;
textBox.Text = list[i].ToString();
This is a bit ugly as it is based on your naming convention for TextBoxes. Perhaps a better solution would be to cache the list of text blocks prior to your loop:
var textBoxes = new[] { textBx1, textBx2, textBx3 };
Then you can simply index into the array:
textBoxes[i].Text = list[i].ToString();
+5
source to share
+1 to Matt. Here is a complete solution that works:
string TextBoxPrefix = "textBx";
foreach (Control CurrentControl in this.Controls)
{
if (CurrentControl is TextBox)
{
if (CurrentControl.Name.StartsWith(TextBoxPrefix)) {
int TextBoxNumber = System.Convert.ToInt16(CurrentControl.Name.Substring(TextBoxPrefix.Length));
if (TextBoxNumber <= (list.Count - 1))
{
CurrentControl.Text = list[TextBoxNumber].ToString();
}
}
}
}
+2
source to share