I have have some code which adds new cells to a table and fills them with text boxes.
The way I’ve coded it so far works fine:
TableCell tCell1 = new TableCell(); TableCell tCell2 = new TableCell(); TableCell tCell3 = new TableCell(); TableCell tCell4 = new TableCell(); TableCell tCell5 = new TableCell(); TableCell tCell6 = new TableCell(); TableCell tCell7 = new TableCell(); TextBox txt1 = new TextBox(); TextBox txt2 = new TextBox(); TextBox txt3 = new TextBox(); TextBox txt4 = new TextBox(); TextBox txt5 = new TextBox(); TextBox txt6 = new TextBox(); TextBox txt7 = new TextBox(); tCell1.Controls.Add(txt1); tCell2.Controls.Add(txt2); tCell3.Controls.Add(txt3); tCell4.Controls.Add(txt4); tCell5.Controls.Add(txt5); tCell6.Controls.Add(txt6); tCell7.Controls.Add(txt7); tRow.Cells.Add(tCell1); tRow.Cells.Add(tCell2); tRow.Cells.Add(tCell3); tRow.Cells.Add(tCell4); tRow.Cells.Add(tCell5); tRow.Cells.Add(tCell6); tRow.Cells.Add(tCell7);
As you can see there’s basically 4 instructions getting repeated 7 times. I’m sure there has to be a way to accomplish this with just 4 lines of code within a FOR loop and having all the names dynamically assigned but I just can’t seem to find anything that would point me in the direction of how to do it.
Something like the following is what I’m after:
for (int i = 0; i < 6; i++) { TableCell tCell[i] = new TableCell(); TextBox txt[i] = new TextBox(); tCell[i].Controls.Add(txt[i]); tRow.Cells.Add(tCell[i]); }
Any help would be much appreciated.
I think this should do it:
Make sure that 6 is changed to a 7.