当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Reference controls (Table) dynamically in code behinde

问题描述:

I would like to know if it is possible to fill different tables with one foreach.

I have 5 table´s tbl0, tbl1, tbl2, tbl3, tbl4 and at the moment i use the code below one time per table.

//fill *dtTable* with SQL

foreach (DataRow dr in dtTable.Rows)

{

TableHeaderRow tHRow = new TableHeaderRow();

TableHeaderCell tHeader = new TableHeaderCell();

tHeader.Text = dr.Field<string>("Loc");

tHRow.Cells.Add(tHeader);

tbl0.Rows.Add(tHRow);

//fill 'hl' with sql

tCell.Controls.Add(hl);

tRow.Controls.Add(tCell);

tbl0.Rows.Add(tRow);

}

I thougt of something like:

 //fill *dtTable* with SQL

int i = 0;

foreach (DataRow dr in dtTable.Rows)

{

string TABLENAME = "tbl"+i;

TableHeaderRow tHRow = new TableHeaderRow();

TableHeaderCell tHeader = new TableHeaderCell();

tHeader.Text = dr.Field<string>("Loc");

tHRow.Cells.Add(tHeader);

(Table)this.FindControl(TABLENAME).Rows.Add(tHRow); // does not funktion, just an idea

//fill 'hl' with sql

tCell.Controls.Add(hl);

tRow.Controls.Add(tCell);

(Table)this.FindControl(TABLENAME).Rows.Add(tRow); // does not funktion, just an idea

i++;

}

How can i have an sort of dynamic TableName so i wont need the same code five times?

网友答案:

Another approach:

int i = 0;
var tables = new List<Table>();
tables.Add(tbl0);
tables.Add(tbl1);
tables.Add(tbl2);
tables.Add(tbl3);
tables.Add(tbl4);


foreach (DataRow dr in dtTable.Rows)
{   
    // validation
   if(i>tables.Count)
   {
      return;
   }

   var tbl in tables[i];
   TableHeaderRow tHRow = new TableHeaderRow();
   TableHeaderCell tHeader = new TableHeaderCell();
   tHeader.Text = dr.Field<string>("Loc");
   tHRow.Cells.Add(tHeader);

   tbl.Rows.Add(tHRow);

   //fill 'hl' with sql

   tCell.Controls.Add(hl);
   tRow.Controls.Add(tCell);

   tbl.Rows.Add(tRow);
   i++;
}

I don't like to use (Table)this.FindControl(TABLENAME).Rows.Add(tRow); because maybe in the future you will change the id of the tables so you will have to change the function as well.

网友答案:

One possible way to ensure you're not needing repeat the same code would be to iterate over all of your tables as well.

foreach (var table in new [] {tbl0, tbl1, tbl2, tbl3, tbl4}) {
    foreach (DataRow dr in table.Rows) {         
        string TABLENAME = "tbl"+i; 

        TableHeaderRow tHRow = new TableHeaderRow();
        TableHeaderCell tHeader = new TableHeaderCell();
        tHeader.Text = dr.Field<string>("Loc");
        tHRow.Cells.Add(tHeader);

        (Table)this.FindControl(TABLENAME).Rows.Add(tHRow);

        //fill 'hl' with sql

        tCell.Controls.Add(hl);
        tRow.Controls.Add(tCell);

        (Table)this.FindControl(TABLENAME).Rows.Add(tRow);
        i++;
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: