复制代码 代码如下:
<asp:GridView runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server" OnCheckedChanged="CheckAll_CheckedChanged" AutoPostBack="true" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="num" HeaderText="num" SortExpression="num" />
</Columns>
</asp:GridView>
其中关于数据的获取不是重点,所以就选择了使用sqldatasource控件来实现数据的获取。 GridView中使用了BoundField绑定了ID,num这两个数据表的字段。在上面的HTML代码中,使用了模板列
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server" OnCheckedChanged="CheckAll_CheckedChanged" AutoPostBack="true" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
复制代码 代码如下:
protected void CheckAll_CheckedChanged(object sender,EventArgs e)
{
CheckBox ck = sender as CheckBox;
if (ck != null)
{
System.Web.UI.WebControls.GridView g = ck.NamingContainer.NamingContainer as System.Web.UI.WebControls.GridView;
for (Int32 i = 0; i < g.Rows.Count; i++)
{
(g.Rows[i].FindControl("CheckBox1") as CheckBox).Checked = ck.Checked;
}
}
}
protected void CheckBox1_CheckedChanged(object sender,EventArgs e)
{
var count = 0;
CheckBox ck = sender as CheckBox;
if (ck != null)
{
System.Web.UI.WebControls.GridView g = ck.NamingContainer.NamingContainer as System.Web.UI.WebControls.GridView;
for (Int32 i = 0; i < g.Rows.Count; i++)
{
if ((g.Rows[i].FindControl("CheckBox1") as CheckBox).Checked)
{
count++;
}
}
(g.HeaderRow.FindControl("CheckAll") as CheckBox).Checked =count==g.Rows.Count;
}
}
复制代码 代码如下:
<script type="text/javascript">
$(function() {
$("#GridView1 :checkbox").eq(0).click(function() {
if ($(this).is(":checked")) {
$(this).parent().parent().nextAll().find(":checkbox").attr("checked", "checked");
}
else {
$(this).parent().parent().nextAll().find(":checkbox").removeAttr("checked");
}
});
$("#GridView1 :checkbox").not($("#GridView1 :checkbox:first")).click(function() {
if ($(this).is(":checked")) {
if ($("#GridView1 :checked").length == $("#GridView1 :checkbox").length - 1) {
$("#GridView1 :checkbox").eq(0).attr("checked", "checked");
}
}
else {
$("#GridView1 :checkbox").eq(0).removeAttr("checked");
}
});
});
</script>
新闻热点
疑难解答
图片精选