JS在GridView中实现CheckBox全选和非全选 及Gridview批量删除使用技巧
1.JS在GridView中实现CheckBox全选和非全选
在Gridvew中添加一模板列,并在该模板列中添加一客户端CheckBox,起名叫CheckAll,在访模板的项模板中添加一个服务端CheckBox,名叫CheckOne,
下面是实现的JS代码:
<script type="text/javascript">
function SelectAll(oCheck)
{
var oTable = document.getElementById("GridView解析之后的tableID"); // 红色ID可以通过运行页面查看源文件获得
if (oTable)
{
var oInputs = oTable.getElementsByTagName("input"); // 得到table里面的所有input控件
for (var i = 0; i < oInputs.length; i++)
{
if (oInputs[i].type == "checkbox") // 判断是否是CheckBox
{
oInputs[i].checked = oCheck.checked;
}
}
}
}
</script>
在GridView的该模板列的头模板做如下设置调用
<HeaderTemplate>
<input id="chkSelectAll" type="checkbox" value="全选" onclick="SelectAll(this)" />
</HeaderTemplate>
2.GridView在使用上术checkbox实现批量删除技巧
因为checkBOX没有CommandArgument属性,且不能绑定Id于Text属性上。
我们将主键ID可以绑定到CheckBox的CssClass、ToolsTip等属性上
编辑模板,选中CheckBox那一列,在绑定模板中,勾上显示所有属性!在其CSSClass属性中绑定主键ID 。
如下图所示:。
其批量删除代码如下
private void btn_Delete( object sender , EventArgs e )
{
for( int i =0; i < GridView1.Row.Count ; i ++)
{
// 查找每一行的CheckBox
// CheckBox chk= this.GridView1.Rows[i].FindControl( "CheckOne") as CheckBox ; // 这个和下面的一样
CheckBox chk= this.GridView1.Rows[i].Cell[0].FindControl( "CheckOne") as CheckBox
if( chk != null )
if( chk.Checked )
{
string id = chk.CssClass ;
// 接下来可以一行一行删除,或组合成一条SQL语句进行删除了
}
}
this.DataBind(); // GridView1.DataBind();
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步