前言:这两天在维护ASP.NET的项目,需要做一个checkbox来选择数据进行导出,下面提供两种解决思路
1、ASP:CheckBox
asp:CheckBox自带控件,没有Value值
<asp:Repeater runat="server" ID="Repeater1"> <ItemTemplate> <tr> <td> <%#Eval("borrow_user_name")%> </td> <td> <%#Eval("borrow_book_name")%> </td> <td> <%#Eval("borrow_begin_date")%> </td> <td> <%#Eval("borrow_state").ToString() == "0" ? "未归还" : "已归还"%> <%--隐藏域传值--%> <asp:HiddenField ID="HiddenField1" Value='<%#Eval("borrow_id")%>' runat="server" /> <asp:CheckBox ID="CheckBox3" runat="server" /> </td> </tr> </ItemTemplate> </asp:Repeater>
protected void btnExport_Click(object sender, EventArgs e) { CheckBox checkbox = new CheckBox(); //创建对象 HiddenField id; //创建对象 for (int i = 0; i < Repeater1.Items.Count; i++) { checkbox = (CheckBox)Repeater1.Items[i].FindControl("CheckBox3");//取对象 id = (HiddenField)Repeater1.Items[i].FindControl("HiddenField1");//取对象 if (checkbox.Checked == true) //是否被选中 { int borrowId = int.Parse(id.Value.ToString()); //赋值 } }
2、 CheckBox
html 的 CheckBox 能赋值给Value
<div id="listBoxMain"> <table id="table1"> <tr> <td id="td4" class="td44"> 选中 </td> <td id="td1"> 借阅人 </td> <td id="td2"> 书籍名 </td> <td id="td3"> 开始时间 </td> </tr> <asp:Repeater ID="Repeater1" runat="server"> <ItemTemplate> <tr> <td class="td44"> <%--关键是id 和 runat="server" --%> <input type="checkbox" id="che" runat="server" value='<%#Eval("borrow_id")%>' class="che2" /> </td> <td> <%#Eval("borrow_book_name")%> </td> <td> <%#Eval("borrow_begin_date")%> </td> <td> <%#Eval("borrow_user_name")%> </td> </tr> </ItemTemplate> </asp:Repeater> </table> </div>
protected void btnExport_Click(object sender, EventArgs e) { //创建 html 的对象 HtmlInputCheckBox che = new HtmlInputCheckBox(); for (int i = 0; i < Repeater1.Items.Count; i++) { che = (HtmlInputCheckBox)Repeater1.Items[i].FindControl("che"); if (che.Checked == true) //是否被选中 { string j = che.Value; //赋值 int borrowId = int.Parse(j); //转换 } } }