asp.net中gridview的checkbox使用总结

时间:2021-11-29 14:03:55

1.在gridview中的<column>中加入

                   <asp:TemplateField HeaderText="选择">
<ItemTemplate>
<asp:CheckBox id="checkboxid" runat="Server"/>
</ItemTemplate>
</asp:TemplateField>

2.cs文件中加button按钮的方法

        protected void checkboxcheck_Click(object sender, EventArgs e)
{
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("checkboxid");
if (cbox.Checked == true)
{
udal.alreadyExam(int.Parse(GridView1.DataKeys[i].Value.ToString()), int.Parse(GridView1.DataKeys[i].Value.ToString()));
}
}
GridView1.DataBind();
}

  关键在于for循环中gv.rows.count-1

和里面的控件强制转换、gv.datakey[i].value

3.全选按钮

是外部和gv无关的checkbox,它的checkchanged改变事件中加入

protected void 全选_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("checkboxid");
if (checkboxbutton.Checked == true)
{
cbox.Checked = true;
}
else
{
cbox.Checked = false;
}
}
}

  实现全选反全选