GridView联合CheckBox实现全选功能[百度空间搜集]
用服务器端的方法:
在页面上放一个gridview控件,配置好数据源,编辑列,添加一个模版列,再编辑模版,放入一个checkbox控件。代码如下:
DataKeyNames="AreaID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="AreaID" HeaderText="AreaID" ReadOnly="True" SortExpression="AreaID"/>
<asp:BoundField DataField="CityID" HeaderText="CityID" SortExpression="CityID"/>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" AutoPostBack="True" OnCheckedChanged="chkAll_CheckedChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkItem" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
后台cs代码:
{
for (int i =0; i <this.GridView1.Rows.Count; i++)
{
((CheckBox)GridView1.Rows[i].FindControl("chkItem")).Checked = ((CheckBox)this.GridView1.HeaderRow.FindControl("chkAll")).Checked;
}
}
用脚本实现:
DataKeyNames="AreaID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="AreaID" HeaderText="AreaID" ReadOnly="True" SortExpression="AreaID"/>
<asp:BoundField DataField="CityID" HeaderText="CityID" SortExpression="CityID"/>
<asp:TemplateField>
<HeaderTemplate>
<input id="chkAll" onclick="SelectAll(this)"; type=checkbox>
</HeaderTemplate>
<ItemTemplate>
<input id="chkItem" type=checkbox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
再客户端写javascript
function SelectAll(chkbox)
{
var box=chkbox;
state=theBox.checked;
elem=box.form.elements;
for(i=0;i<elem.length;i++)
if(elem[i].type=="checkbox"&& elem[i].id!=box.id)
{
if(elem[i].checked!=state)
{
elem[i].click();
}
}
}
</script>
=========================================================
<asp:TemplateColumn HeaderText="<input type=checkbox name='selectall' onClick='SelectAll(document.Form1)'>全选">
<ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server"> </asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
function SelectAll(frm)
{
for (var i=0;i <frm.elements.length;i++)
frm.elements[i].checked = frm.selectall.checked;
}
function CheckSelect(frm)
{
var col=frm.elements;
var obj=frm.selectall;
var intEls=0,intChks=0;
for(var i=0;i <col.length;i++)
{
if(col[i].type=="checkbox"&&col[i].name!="selectall")
{
intEls++;
if(col[i].checked)
intChks++;
}
}
obj.checked=(intEls==intChks);
}