首先是把checkbox添加到表头,需要用到gridview的模板列
<asp:TemplateField HeaderText ="全选" ItemStyle-HorizontalAlign="Center">
<HeaderTemplate>
<asp:CheckBox ID="ckhead" runat="server" Text="全选" AutoPostBack="True"
oncheckedchanged="ckhead_CheckedChanged"/>
</HeaderTemplate>
<ItemTemplate>
<input id="ck" type="checkbox" name="chkGet" runat="server" value='<%#Eval("UserID") %>' />
</ItemTemplate>
第一个checkbox是显示在gridview的头上的,第二个checkbox是显示在girdview的每一行的,需要注意的是,第一个checkbox是服务器控件,要把回发设置为真
AutoPostBack="True" ,在oncheckedchanged事件里写全选事件,
protected void ckhead_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb=(CheckBox)this.GridView1.HeaderRow.FindControl("ckhead");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
HtmlInputCheckBox chk = (HtmlInputCheckBox)GridView1.Rows[i].FindControl("ck");
chk.Checked = cb.Checked;
}
}
这只是让控件选中而已,还有一步就是操作选中的项,
想操作选中项,必须先获取
protected void btn_lock_Click(object sender, EventArgs e)
{
bool status = false;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
HtmlInputCheckBox chk = (HtmlInputCheckBox)GridView1.Rows[i].FindControl("ck"); //获取选中的项
if (chk.Checked == true) //判断状态
{
long uid = Convert.ToInt32(chk.Value);
if (BLLFuntions.UpdateModel(new tb_user { UserID = uid }, new tb_user { IsLockStock = 1 }))
{ status = true; }
else
{
status = false;
break;
}
}
}
if (status)
{
MessageBox.Show(this, "操作已成功");
Bind();
}
else
{
MessageBox.Show(this, "操作已失败");
Bind();
}
}
大概就这样了……希望对读者有所帮助……