在表中动态添加下拉列表

本文关键字:添加 下拉列表 动态 | 更新日期: 2023-09-27 18:29:34

我有一个表,无法动态填充数据。。。它只显示最后一个表单元格,其余行为空。下拉列表似乎以正确的方式弹出。

DataTable dtt1 = (DataTable)Session["dbasecolumns"];
    int l = dtt1.Columns.Count;
    string[] sqlcolumn = new string[l];

    ***for (int j = 0; j < dtt1.Columns.Count; j++)
    {
        sqlcolumn[j] = dtt1.Columns[j].ColumnName;
    }
    Session["excel"] = sqlcolumn;***

DropDownList drd = new DropDownList();
    foreach (String colname in sqlcolumn)
    {
        drd.Items.Add(colname);
    }
    Table mytable = new Table();
    mytable.Visible = true;
    for (int rowctr = 0; rowctr < sqlcolumn.Length; rowctr++)
    {
        TableRow myrow = new TableRow();
        mytable.Rows.Add(myrow);

        for (int cellctr = 0; cellctr < 1; cellctr++)
        {
            TableCell mycell = new TableCell();
            mycell.Controls.Add(drd);
            myrow.Cells.Add(mycell);
        }
      ***mytable.Rows.Add(myrow);***
     }
    Panel1.Controls.Add(mytable);

提前感谢

在表中动态添加下拉列表

DataTable dtt1 = (DataTable)Session["dbasecolumns"];
int l = dtt1.Columns.Count;
string[] sqlcolumn = new string[l];
DropDownList drd = new DropDownList();
foreach (String colname in sqlcolumn)
{
    drd.Items.Add(colname);
}

您正在对sqlcolumn进行迭代,但您的sqlcolumn为空。它没有任何值来填充您的DropDownList。在这里,您定义了特定长度的字符串array,但它不包含任何值。(希望我的方向是正确的,因为我只能看到你们代码的这么多)。

您可以直接从数据表中填写DropDownList

DataTable dtt1 = (DataTable)Session["dbasecolumns"];   
DropDownList drd = new DropDownList();
for (int i = 0; dtt1 .Rows.Count > i; i++)
{
    dhgdh.Items.Add(dt.Rows[i]["dbasecolumns"].ToString());
}

这将工作

for (int rowctr = 0; rowctr <= sqlcolumn.Length; rowctr++)
{
    TableRow myrow = new TableRow();
    mytable.Rows.Add(myrow);
    // for (int cellctr = 0; cellctr <= 1; cellctr++)
    //{
    DropDownList drd = new DropDownList();
    foreach (String colname in sqlcolumn)
    {
        drd.Items.Add(colname);
    }
    TableCell mycell = new TableCell();
    mycell.Controls.Add(drd);
    myrow.Cells.Add(mycell);
    //}
    mytable.Rows.Add(myrow);
}

我添加了一个包含两列的表。每列都有一个dropdownlist,其中listitems来自SQL数据库和Excel文件。

 for (int rowctr = 0; rowctr <= sqlcolumn.Length; rowctr++)
    {
          mycell = new TableCell();
        TableCell mycell1 = new TableCell();
         for (int cellctr = 0; cellctr < 1; cellctr++)
         {
            DropDownList drd = new DropDownList();
            DropDownList drd1 = new DropDownList();
            foreach (String colname in sqlcolumn)
            {
                drd.Items.Add(colname);                    
            }
            foreach (string colnames in excel)
            {
                drd1.Items.Add(colnames);
            }                
            TableRow myrow = new TableRow();           
            mycell.Controls.Add(drd);
            mycell1.Controls.Add(drd1);            
            myrow.Cells.Add(mycell);
            myrow.Cells.Add(mycell1);
            mytable.Rows.Add(myrow);
}
Panel1.Controls.Add(mytable);