---
title: "GridView中用CheckBox实现全选功能"
author: "kingfly.good"
date: "2009-07-29T11:31:30Z"
tags: []
slug: "gridview-checkbox"
draft: false
lastmod: "2009-07-29T23:03:23Z"
id: 435154
url: "https://kingfly-good.iteye.com/blog/435154"
---

在.aspx的<title></title>标签下添加如下脚本：

```js

<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中的模板列添加如下代码：

```C#

<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中的行来计算选中行的总数

```C#

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++;                                                
     }                       
}            

```