得到复选框选中的值,并把它放在一个行的表
问题描述:
海兰所有,得到复选框选中的值,并把它放在一个行的表
我正在开发一个web应用程序,我试图用一个CheckBoxList的。我希望对于该复选框列表中的每个选定项目在表格中创建一个新行。因此,如果我有5个项目,并且我选中3,我想要一个表格显示3行,并在每行中显示所选项目。这就是我得到什么项目检查:
protected void Button1_Click(object sender, EventArgs e)
{
string str = string.Empty;
foreach (ListItem item in check.Items)
{
str += item.Value;
}
}
我的问题是:如何创建一个表与选定的值?我在一个asp.net应用程序中使用c#
答
您需要在每次回发中重新创建此表,因为它是动态创建的。
这里的工作示例代码:
<asp:CheckBoxList ID="check" runat="server">
<asp:ListItem Text="Item 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item 2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item 3" Value="3"></asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="Apply Selection" OnClick="Button1_Click" />
<asp:Table ID="TblCheck" runat="server"></asp:Table>
代码隐藏:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) RecreateTable();
}
private void RecreateTable()
{
var selected = this.check.Items.Cast<ListItem>().Where(i => i.Selected);
foreach (var item in selected)
{
TableRow row = new TableRow();
TableCell cell = new TableCell();
Label lbl = new Label();
lbl.Text = item.Text;
cell.Controls.Add(lbl);
row.Cells.Add(cell);
this.TblCheck.Rows.Add(row);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//RecreateTable();
}
按钮单击处理程序不必当它从Page_Load中创建反正甚至创建它。