1.首先要在你的GridView的HeaderTemplate项模版里放一个HTML工具栏里的checkbox控件(注意:这里所说的不是标准里边的服务器控件)并在这个控件的onclick事件中调用步骤2里边的函数方法,也就是οnclick="CheckAll(this)"这里边的this就是这个控件的本身,然后在你GridView的ItemTemplate项模版里边放一个标注工具栏里的checkbox控件(注意:这个是服务器控件,和上个正好相反)
<
HeaderTemplate
>
全选 < input id = " Checkbox2 " type = " checkbox " onclick = " CheckAll(this) " />
</ HeaderTemplate >
< ItemTemplate >
< asp:CheckBox ID = " CheckBox1 " runat = " server " />
</ ItemTemplate >
全选 < input id = " Checkbox2 " type = " checkbox " onclick = " CheckAll(this) " />
</ HeaderTemplate >
< ItemTemplate >
< asp:CheckBox ID = " CheckBox1 " runat = " server " />
</ ItemTemplate >
2.要在你实现这个功能的.aspx页面写一个函数方法
代码
<
script type
=
"
text/javascript
"
language
=
"
javascript
"
>
function CheckAll(che)
{
var items = document.getElementsByTagName( " input " );
for (i = 0 ;i < items.length;i ++ )
{
if (items[i].type == " checkbox " )
{
items[i]. checked = che. checked ;
}
}
}
</ script >
function CheckAll(che)
{
var items = document.getElementsByTagName( " input " );
for (i = 0 ;i < items.length;i ++ )
{
if (items[i].type == " checkbox " )
{
items[i]. checked = che. checked ;
}
}
}
</ script >
3.在.CS页面写一个方法,这个方法主要用于获得被选中列ID的集合(注意:这里边的Cells[1].Text中的1指的是ID列在你的GridView行的位置,索引从0开始,第一列即为Cells[0].Text以此类推)
代码
private
string
GetIdS()
{
string ids = string .Empty;
for ( int i = 0 ; i < this .GridView1.Rows.Count; i ++ )
{
CheckBox c = ( this .GridView1.Rows[i].FindControl( " CheckBox1 " )) as CheckBox;
if (c.Checked == true )
{
ids += this .GridView1.Rows[i].Cells[ 1 ].Text + " , " ;
}
}
if (ids.Length > 0 )
{
ids = ids.Substring( 0 , ids.Length - 1 );
}
return ids;
}
{
string ids = string .Empty;
for ( int i = 0 ; i < this .GridView1.Rows.Count; i ++ )
{
CheckBox c = ( this .GridView1.Rows[i].FindControl( " CheckBox1 " )) as CheckBox;
if (c.Checked == true )
{
ids += this .GridView1.Rows[i].Cells[ 1 ].Text + " , " ;
}
}
if (ids.Length > 0 )
{
ids = ids.Substring( 0 , ids.Length - 1 );
}
return ids;
}
4,最后写删除语句,执行sql就可以了,ids就是上个方法返回的ids
string
sql
=
"
delete from [Users] where [Id] in (
"
+
ids
+
"
)
"
;
这样就可以轻松的实现GridView的全选删除功能,由于本人也是一个初学.NET的一个菜鸟把,有写的不明白的地方还请大家多多谅解,多多提出建议,希望对那些初学.NET和我一样的人有所帮助!有不明白的地方可以留言问我。