在DataGrid页眉上添加全选的CheckBox控件

本文介绍了使用JavaScript和C#实现DataGrid中全选和全取消功能的两种方法。方法一是通过JavaScript直接在客户端实现全选操作,提高效率;方法二是利用C#回发到服务端来完成全选逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很简单的方法,就是用js实现:

页面:

AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False">



















后台代码:

private void dgUserList_PreRender(object sender, System.EventArgs e)
{
foreach (DataGridItem item in dgUserList.Controls[0].Controls)
{
if (item.ItemType == ListItemType.Header)
{
CheckBox chkAll=(CheckBox)item.FindControl("chkAll");
System.Text.StringBuilder strScript = new System.Text.StringBuilder("

for(int i=0; i{
strScript.Append(" document.all('" + dgUserList.Items[i].Cells[0].FindControl("chkItem").ClientID + "').checked = bAll; n");
}
strScript.Append(" } n");
strScript.Append(" n");

if(!Page.IsClientScriptBlockRegistered("checkStatus"))
Page.RegisterClientScriptBlock("checkStatus",strScript.ToString());

chkAll.Attributes.Add("onclick","checkStatus()");
return;
}
}

方法2

(一).功能

1. JavaScript检索CheckBox并实现全选和全消功能

用C#等写的CheckBox需要回发到服务端执行,
而用JavaScript可以在直接客户端实现,效率高些

(二).代码

1. DataGrid中的代码主要片段:

//头模板代码

οnclick="javascript:SelectAll(this);">


//项模板代码

2. 在当页加入:

var theBox=tempControl;
xState=theBox.checked;

elem=theBox.form.elements;
for(i=0;i if(elem[i].type=="checkbox" && elem[i].id!=theBox.id)
{
if(elem[i].checked!=xState)
elem[i].click();
}
}

3.当使用者选择好后台代码取得某列CheckBox的值:
for (int i = 0;i {
bool blnIfSelect = ((CheckBox)this.DataGrid.Items[i].FindControl("chkItem")).Checked;
....; //这是可以根据blnIfSelect进行各种操作了
}

[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/631872/viewspace-911218/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/631872/viewspace-911218/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值