I have a working code that has to many lines of repeated code. I would like to write a method to save lines of code.
I have a query that gets the number of registries in the database. The number of registries may vary from 1 to 20. The number of registries is saved in the decimal numberOfLines.
Today I am using 20 if's, that writes 4 textboxes per line for each possible number of lines I have.
If I have only one line it write 1 line of 4 textboxes, if I have 2 lines it writes 2 lines of 4 textboxes and so one.
I will only show the code for the quantity of lines from 1 to 4 just to save space (the rest of the code is just copy/paste and change the textboxes new indexes).
//write the lines according to the number of lines
if (numberOfLines == 1)
{
txt_A1.Text = tableAs.Rows[0][0].ToString();
txt_B1.Text = tableAs.Rows[0][1].ToString();
txt_C1.Text = tableAs.Rows[0][2].ToString();
txt_D1.Text = tableAs.Rows[0][3].ToString();
}
if (numberOfLines ==2)
{
txt_A1.Text = tableAs.Rows[0][0].ToString();
txt_B1.Text = tableAs.Rows[0][1].ToString();
txt_C1.Text = tableAs.Rows[0][2].ToString();
txt_D1.Text = tableAs.Rows[0][3].ToString();
txt_A2.Text = tableAs.Rows[1][0].ToString();
txt_B2.Text = tableAs.Rows[1][1].ToString();
txt_C2.Text = tableAs.Rows[1][2].ToString();
txt_D2.Text = tableAs.Rows[1][3].ToString();
}
if (numberOfLines == 3)
{
txt_A1.Text = tableAs.Rows[0][0].ToString();
txt_B1.Text = tableAs.Rows[0][1].ToString();
txt_C1.Text = tableAs.Rows[0][2].ToString();
txt_D1.Text = tableAs.Rows[0][3].ToString();
txt_A2.Text = tableAs.Rows[1][0].ToString();
txt_B2.Text = tableAs.Rows[1][1].ToString();
txt_C2.Text = tableAs.Rows[1][2].ToString();
txt_D2.Text = tableAs.Rows[1][3].ToString();
txt_A3.Text = tableAs.Rows[2][0].ToString();
txt_B3.Text = tableAs.Rows[2][1].ToString();
txt_C3.Text = tableAs.Rows[2][2].ToString();
txt_D3.Text = tableAs.Rows[2][3].ToString();
}
if (numberOfLines == 4)
{
txt_A1.Text = tableAs.Rows[0][0].ToString();
txt_B1.Text = tableAs.Rows[0][1].ToString();
txt_C1.Text = tableAs.Rows[0][2].ToString();
txt_D1.Text = tableAs.Rows[0][3].ToString();
txt_A2.Text = tableAs.Rows[1][0].ToString();
txt_B2.Text = tableAs.Rows[1][1].ToString();
txt_C2.Text = tableAs.Rows[1][2].ToString();
txt_D2.Text = tableAs.Rows[1][3].ToString();
txt_A3.Text = tableAs.Rows[2][0].ToString();
txt_B3.Text = tableAs.Rows[2][1].ToString();
txt_C3.Text = tableAs.Rows[2][2].ToString();
txt_D3.Text = tableAs.Rows[2][3].ToString();
txt_A4.Text = tableAs.Rows[3][0].ToString();
txt_B4.Text = tableAs.Rows[3][1].ToString();
txt_C4.Text = tableAs.Rows[3][2].ToString();
txt_D4.Text = tableAs.Rows[3][3].ToString();
}
With the amount of possible lines I have (20) the code gets very big, and not as beautiful as I expected (with the use of a method for example).