直接通过GridView的cells取CheckBox的值都是空串,在网上查询之后,有三种解决方案,将其收藏。
一、CheckBoxField取值的方法:
前台代码:
- <asp:GridView ID="GridView1" runat="server" Width="418px">
- <Columns>
- <asp:CheckBoxField DataField="是否有效" HeaderText="有效性" />
- </Columns>
- </asp:GridView>
后台代码:
- CheckBox cb = (CheckBox)GridView_Users.SelectedRow.Cells[6].Controls[0];
- if(cb!=null) CheckBox_Available.Checked = cb.Checked;
二、CheckBox取值:
方法一:(C#)
操作:
- string PKname="";
- foreach (GridViewRow GR in this.GridView1.Rows)
- {
- CheckBox CB = (CheckBox)GR.FindControl("CheckBox1");
- if (CB.Checked)
- {
- PKname += this.GridView1.DataKeys[GR.RowIndex].Value.ToString()+",";
- }
- }
补充:前台<asp:CheckBox ID="CheckBox1" runat="server" Text=' <%#Eval("列名") %>'/>
实例:前台代码
- <Columns>
- <asp:TemplateField HeaderText="选择">
- <HeaderStyle HorizontalAlign="Center" Height="25px" Width="45px" />
- <ItemTemplate>
- <asp:CheckBox ID="ckb" runat="server" />
- </ItemTemplate>
- </asp:TemplateField>
- <asp:BoundField DataField="sid" HeaderText="编号" />
- <asp:BoundField DataField="cname" HeaderText="姓名" />
- </Columns>
实例:后台代码
- foreach (GridViewRow gvr in this.GridView1.Rows)
- {
- Control ctl = gvr.FindControl("ckb");
- CheckBox ck = (CheckBox)ctl;
- if (ck.Checked)
- {
- TableCellCollection cell = gvr.Cells;
- string wid += cell[1].Text+",";
- }
- }
方法二:(VB)
GridView->设置DataKeyNames
- Dim gvr as GridViewRow
- Dim KeyName as string'要的关键字,实际就是数据表的主键.需要事先在GridView1的DataKeyNames中设置.
- Dim i as IntegerFor each gvr in GridView1.Rows
- IF Ctype(gvr.FindControl("CheckBox1"),CheckBox).Checked=True Then
- i=gvr.Rowindex;'GridView行索引
- KeyName=GridView1.DataKeys(i).value;
- ...根据KeyName想做什么做什么吧.
- End If
- Next