c# - 该代码仅创建最后一个复选框,我应该做些什么不同或添加?
问题描述
我想根据链接到站点的喷嘴数量动态创建复选框。
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>
解决方案
将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);
}
推荐阅读
- javascript - firebase 云功能不更新数据
- c# - ML.NET IDataView 返回 csv
- ruby-on-rails - 我从延迟的作业中得到重复的插入到数据库表中
- javascript - Javascript 又神秘了?
- java - 更改 dataTable 选择 JSF 2.2/ Primefaces 上的 inputText
- angular - Angular 6中的过期时间倒计时
- certificate - 如何从 PKCS12 密钥库更改密钥密码
- python - 仅使用 predict() 或 predict_on_batch() 预测批次中的单个时间序列样本
- flutter - 带有 ExpansionTile 的 ReorderableListView
- java - 如何获得打印出对象地址和自定义 toString 的能力