Example:
I have 1000 textboxes in 1 form.
The textboxes names are textbox1, textbox2 ... textbox1000
I want to be able to do the following thing:
String myString = "textbox";
for (int i = 0; i <= 1000; i = i 1)
myString i.Text = "Textbox number " i.ToString()
next
IMPORTANT, solve my goal not my example
My goal is to not write the textbox, and get it from a predefined string, well, like the example
Sorry for the confusion and the edits. Its my first post :/
CodePudding user response:
This is case sensitive and assumes the control is on the form, not say a panel
string txt1 = "textBox1";
var textbox = Controls.OfType<TextBox>().FirstOrDefault(x => x.Name == txt1);
if (textbox != null)
{
textbox.Text = "";
}
In a panel or group-box
var tb = Controls.Find(txt1, true);
if (tb.Length >0)
{
((TextBox)tb[0]).Text = "";
}
Then for 1-1000
for (int index = 0; index < 1000; index )
{
var textbox = Controls.OfType<TextBox>().FirstOrDefault(x => x.Name == $"textBox{index}");
if (textbox != null)
{
textbox.Text = "";
}
}
Edit
var baseText = "Textbox number ";
for (int index = 0; index < 1000; index )
{
var textBox = Controls.OfType<TextBox>().FirstOrDefault(x => x.Name == $"textBox{index}");
if (textBox != null)
{
textBox.Text = $"{baseText}{index}";
}
}
CodePudding user response:
I believe you want to edit the text in a Textbox. You can do like so:
string txt1 = Textbox1.Text;
txt1 = "(Edited Text)" txt1;
And to change the text of Textbox at runtime, you can set the Text property of Textbox to that string.
Textbox1.Text = txt1;
Complete code, will then be:
string txt1 = Textbox1.Text;
txt1 = "(Edited Text)" txt1;
Textbox1.Text = txt1;