`
kingfly.good
  • 浏览: 27074 次
  • 性别: Icon_minigender_1
  • 来自: 成都
最近访客 更多访客>>
社区版块
存档分类
最新评论

GridView中用CheckBox实现全选功能

阅读更多
在.aspx的<title></title>标签下添加如下脚本:
<script type="text/javascript" language="javascript">
function SelectAllCheckboxes(spanChk)
{
   var oItem = spanChk.children;
   var theBox=(spanChk.type=="checkbox")?spanChk:spanChk.children.item[0];
   xState=theBox.checked;
   elm=theBox.form.elements;
   for(i=0;i<elm.length;i++)
   if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)
   {
      if(elm[i].checked!=xState)
      elm[i].click();
   }
}
</script>

在GridView中的模板列添加如下代码:
<asp:TemplateField>
<HeaderTemplate>
<input id="chkall" type="checkbox" onclick="SelectAllCheckboxes(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
</ItemTemplate>
<HeaderStyle CssClass="table_head" />
<ItemStyle Width="15px" />
</asp:TemplateField>

<asp:TemplateField HeaderText="PersonId" Visible="False">
<ItemTemplate>
<asp:Label ID="lblPersonId" runat="server" Text='<%# bind("PersonId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>


在后台通过遍历GridView中的行来计算选中行的总数
int count=0;
foreach (GridViewRow gvr in PersonGridView.Rows)
{
    bool isChecked = ((CheckBox)gvr.Cells[0].FindControl("chk")).Checked;
    if (isChecked)
    {            
        int iPersonId = Int32.Parse(((Label)gvr.Cells[1].FindControl("lblPersonId")).Text);
        string strSql = "DELETE SYS_PERSON WHERE PersonId=@PersonId";
        SqlConnection con = new SqlConnection(SqlHelper.ConnectionString);
        SqlCommand cmd = new SqlCommand(strSql, con);
        cmd.Parameters.Add("@PersonId",SqlDbType.Int);      
        cmd.Parameters["@PersonId"].Value = iPersonId;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        count++;                                                
     }                       
}            
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics