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++;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值