I have 10 textboxes(tb1,tb2,tb3,...) and when I press the button , the 10 textboxes will be filled with values based on the startingNum input by user, e.g:10, by addition ( 1, 2, 3,..) according to the sequence of the 10 textboxes.
My code is working but is it possible to use loops or any better way to improve my codes?
private void genBtn_Click(object sender, EventArgs e)
{
firstNum.Text = alphaBox.Text (intFirst 0).ToString();
SecondNum.Text = alphaBox.Text (intFirst 1).ToString();
thirdNum.Text = alphaBox.Text (intFirst 2).ToString();
fourthNum.Text = alphaBox.Text (intFirst 3).ToString();
fifthNum.Text = alphaBox.Text (intFirst 4).ToString();
sixNum.Text = alphaBox.Text (intFirst 5).ToString();
seventhNum.Text = alphaBox.Text (intFirst 6).ToString();
eighthNum.Text = alphaBox.Text (intFirst 7).ToString();
ninthNum.Text = alphaBox.Text (intFirst 8).ToString();
tenthNum.Text = alphaBox.Text (intFirst 9).ToString();
}
CodePudding user response:
Maybe you could put them in an array or list and use this LINQ approach:
var allTextBoxes = new[]{firstNum, SecondNum, thirdNum, ... };
int intFirst = 10; // actually user input
allTextBoxes.Take(intFirst).Select((txt, index) => (txt, index)).ToList()
.ForEach(x => x.txt.Text = alphaBox.Text (intFirst x.index).ToString());
Of course you should add the TextBoxes to the array only once and not in this method.
CodePudding user response:
You can loop on textboxes doing :
int i=0;
foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
tb.Text = alphaBox.Text (intFirst i).ToString();
i ;
}