This is a piece of the code i have done but i want to make it shorter.
textBox0.Text = array[0];
textBox1.Text = array[1];
textBox2.Text = array[2];
textBox3.Text = array[3];
textBox4.Text = array[4];
....
This is how i want it :
int a = 0;
for(int N=0; N ; N<5)
textboxN.text = array[a];
a ;
CodePudding user response:
If the textboxes have a common container, like a Panel or GroupBox control, you can do this:
TextBox[] textBoxes = container.Controls.OfType<TextBox>().ToArray();
And then later:
for(int N = 0; N < array.Length; N )
{
textbox[N].Text = array[N];
}
Note the container can even be your form, but in this case you must make sure you don't have an other TextBox controls on the form. That's why something like a borderless panel might be useful here; it gives you a logical section on the form to keep these fields separate in a way that can be invisible to the user.
CodePudding user response:
This could help you:
List<TextBox> textBoxes = new List<TextBox>() {textBox0, textBox1, textBox2, textBox3, textBox4 };
for(int i = 0; i < textBoxes.Count; i )
{
textBoxes[i].Text = array[i];
}
You put the text boxes into a list and then go through them and set the values. Here is that as a one-liner
textBoxes.Foreach(x => x.Text = array[textBoxes.IndexOf(x)]);
CodePudding user response:
Try This
var textBoxList = new List<Control>();
foreach (var control in this.Controls)
{
if (control.GetType().Name == "TextBox")
{
textBoxList.Add(control as Control);
}
}
textBoxList = textBoxList.OrderBy(t => t.Name).ToList();
for (var i = 0; i < textBoxList.Count; i )
{
textBoxList[i].Text = array[i];
}
CodePudding user response:
You can try something like this, but it makes some sense if you have dozens textboxes
var maxIndex=array.length;
foreach (var control in this.Controls)
{
var textBox = control as TextBox;
if (textBox != null)
{
var i= Convert.ToInt16( textBox.Name.Substring(6));
if ( i<maxIndex) textBox.Text=array[i];
}
}