GridView的CheckBox实现全选(asp.net2.0)
一,在GridView模版里放两个html的checkbox 控件,在ItemTemplate里添加一个chkSingle,在HeaderTemplate里添加另一个chkAll。
二,脚本文件,复制到<head></head>之间
<script language="javascript">
function SelectAll (chkVal, idVal)
{
var thisfrm = document.forms[0];
var iCheckAll;
var iCounts=0;
var iCheckCount=0;
for (i=0; i<thisfrm.length; i++)
{
if(thisfrm.elements[i].id.indexOf('chkAll') != -1 )
{
iCheckAll=i;
}
if(thisfrm.elements[i].id.indexOf('chkSingle') != -1 )
iCounts++;
}
// 查找Forms里面所有的元素
for (i=0; i<thisfrm.length; i++)
{
// 查找模板头中的CheckBox
if (idVal.indexOf ('chkAll') != -1)
{
if(chkVal == true)
{
thisfrm.elements[i].checked = true;
}
else
{
thisfrm.elements[i].checked = false;
}
} // if
// 如果除题头以外的项没有全选上则取消题头的选择
else if (idVal.indexOf ('chkSingle') != -1)
{
if(thisfrm.elements[i].checked == false)
{
thisfrm.elements[iCheckAll].checked =false;
}
}
} // for
for (i=0; i<thisfrm.length; i++)
{
if(thisfrm.elements[i].id.indexOf('chkSingle') != -1 )
{
if(thisfrm.elements[i].checked == true)
iCheckCount++;
}
}
if(iCheckCount==iCounts)
thisfrm.elements[iCheckAll].checked =true;
}
</script>
三,添加到客户端执行
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox chk = (CheckBox)e.Row.Cells[0].FindControl("chkAll");
chk.Attributes.Add("onclick", "javascript:return SelectAll(this.checked,this.id);");
}
if (!(e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.Footer))
{
CheckBox chk = (CheckBox)e.Row.Cells[0].FindControl("chkSingle");
chk.Attributes.Add("onclick", "javascript:return SelectAll(this.checked,this.id);");
}
}
四,//服务端处理
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox m_Chk = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chkSingle");
if (m_Chk.Checked)
{
m_PartSerial = GridView1.Rows[i].Cells[1].Text; //仪器序列号
m_Sqlstr = "insert into CS_Service_Notification_Parts (EQ_SN,PART_SN) "
+ "values('"+m_EquSerial+"','"+m_PartSerial+"')";
SqlHelper.ExecuteNonQuery(m_Sqlstr);
m_Flag = true;
}
}