首页 > 解决方案 > 该代码仅创建最后一个复选框,我应该做些什么不同或添加?

问题描述

我想根据链接到站点的喷嘴数量动态创建复选框。

Table table = new Table();

List<string> check = Helpers.getNozzle(Selected.SelectedValue);
//create a new row, cell and checkbox
TableRow row = new TableRow();
TableCell cell = new TableCell();
CheckBox cb = new CheckBox();

foreach (var item in check)
{
    //set some checkbox properties
    cb.Text = "Nozzle " + item;

    //add the checkbox to the cell
    cell.Controls.Add(cb);

    //the cell to the row
    row.Controls.Add(cell);
}

//and the row to the table
table.Controls.Add(row);
//finally add the table to the page
controleplaceholder.Controls.Add(table);

foreach 和 for 循环都只创建最后一个复选框。我的问题是我错过了什么以及为什么它只创建最后一个复选框。

这是aspx的一面

<tr style="color: white">
    <td>Nozzle(s):
    </td>
    <td id="checkboxes" runat="server">
        <asp:PlaceHolder runat="server" ID="controleplaceholder" />     
        
    </td>
</tr>

标签: c#asp.net

解决方案


TableCell cell = new TableCell();&移入CheckBox cb = new CheckBox();内部foreach,因为您只是重命名并将相同的对象再次添加到row.Controls其中只会添加单个控件。

foreach (var item in check)
{
    TableCell cell = new TableCell();
    CheckBox cb = new CheckBox();

    //set some checkbox properties
    cb.Text = "Nozzle " + item;

    //add the checkbox to the cell
    cell.Controls.Add(cb);

    //the cell to the row
    row.Controls.Add(cell);
}

推荐阅读