How to simplify code using a loop?

1

How can I simplify the code below using a loop, I am in doubt because of the names of the labels that are sequential, as I put something variable in FieldName1, NomeCampo2 , ..., NomeCampoX .

lblNomeCampo1.Text = dt.Rows[1][0].ToString()+":";
lblCampo1.Text = dt.Rows[1][1].ToString();
lblNomeCampo2.Text = dt.Rows[2][0].ToString() + ":";
lblCampo2.Text = dt.Rows[2][1].ToString();
lblNomeCampo3.Text = dt.Rows[3][0].ToString() + ":";
lblCampo3.Text = dt.Rows[3][1].ToString();
lblNomeCampo4.Text = dt.Rows[4][0].ToString() + ":";
lblCampo4.Text = dt.Rows[4][1].ToString();
lblNomeCampo5.Text = dt.Rows[5][0].ToString() + ":";
lblCampo5.Text = dt.Rows[5][1].ToString();
lblNomeCampo6.Text = dt.Rows[6][0].ToString() + ":";
lblCampo6.Text = dt.Rows[6][1].ToString();
lblNomeCampo7.Text = dt.Rows[7][0].ToString() + ":";
lblCampo7.Text = dt.Rows[7][1].ToString();
lblNomeCampo8.Text = dt.Rows[8][0].ToString() + ":";
lblCampo8.Text = dt.Rows[8][1].ToString();
lblNomeCampo9.Text = dt.Rows[9][0].ToString() + ":";
lblCampo9.Text = dt.Rows[9][1].ToString();
lblNomeCampo10.Text = dt.Rows[10][0].ToString() + ":";
lblCampo10.Text = dt.Rows[10][1].ToString();
    
asked by anonymous 30.10.2017 / 12:18

2 answers

3

Essentially it does not look this way. I would give it some thought, but I do not think it will make up for it.

You can restructure the form that handles this, so that the fields are array elements too, so everything that surrounds them can be used with a loop. Here you could do this:

lblNomeCampo[i].Text = dt.Rows[i][0].ToString()+":";
lblCampo[i].Text = dt.Rows[i][1].ToString();

Every time you have multiple variables with names that have a sequence of numbers as a suffix, you can substitute an array (or similar structure) simply and simply, ie simply change the number fixed by array index.

Obviously you have to create the array and create the screen objects over the elements of array .

Each element of the array is a variable like any other, nothing changes in it except the fact that it is accessed by the set of the name plus the index. Then treat them this way.

This solution is independent of language, although it would be better to know what it is (by what I understand it is C #).

    
30.10.2017 / 12:29
0

It is not the best way but it could do something like this, I do not understand much of C #, but the path is more or less this:

for (var i=1; i <= 10; i++) {
   Eval("lblNomeCampo"+i+".Text = dt.Rows["+i+"][0].ToString() + \":\";");
   Eval("lblCampo"+i+".Text = dt.Rows["+i+"][1].ToString() + \":\";");
}

I suggest something more elaborate, type:

   foreach (int i in dt.Rows) {
       lblNomeCampo[i].Text = dt.Rows[i][0].ToString() + ":";
       lblCampo[i].Text = dt.Rows[i][1].ToString() + ":";
   }

Leave the fields in the form like this:

name="lblNomeCampo[]"

name="lblCampo[]"
    
31.10.2017 / 12:37