在DataGrid中利用CheckBox全选所有行
效果图:
背景:
asp.net中的DataGrid用复选框全选或全不选其中所有行
思路:
因为经常有这方面的需求,以往都是在客户端写脚本,通用性差。所以我想把该功能写成一个控件,以达到复用的效果。功能包括:
1、DataGrid中放置CheckBox
2、点击列头的CheckBox以实现全选或全不选,并且改动作不会提交到服务端,即没有刷新现象
3、利用静态方法static注册客户端的JavaScript代码
怎么使用:
在.aspx文件中Grid中的列注册一个TagPrefix
<%@ Register TagPrefix="GridSelectCheckBox" Namespace="solCommon.Web.UI.DataGrid"
Assembly="ProjectAssembly" %>
在DataGrid中添加选择列
<asp:datagrid ...>
...
<Columns>
<GridSelectCheckBox:DGCheckBoxColumn />
...
</Columns>
...
</asp:datagrid>
在Page_Load方法中注册客户端代码
DGCheckBoxColumn.RegisterClientCheckEvents(this,"Form1");
//主意:上面的一行一定要在DataGrid绑定数据之后,要不会出错的
eg:
if(!Page.IsPostBack)
{
DataGrid1.DataSource = table;
DataGrid1.DataBind();
}
DGCheckBoxColumn.RegisterClientCheckEvents(this,"Form1");
获取所有选择中的行的索引:
// since we know that our column in the grid is the first one ...
DGCheckBoxColumn dgchkbxCol = (DGCheckBoxColumn)myGrid.Columns[0];
// iterate through the selection
foreach (int i in dgchkbxCol.SelectedIndexes)
{
// do something ...
}
付.aspx得代码如下:
<%@ Page language="c#" Codebehind="DGCheckBoxTest.aspx.cs" AutoEventWireup="false" Inherits="SchoolMark.Student.DGCheckBoxTest" %>
<%@ Register TagPrefix="GridSelectCheckBox" Namespace="WebControlLib" Assembly="WebControlLib" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>DGCheckBoxTest</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 8px" runat="server"
Width="456px" Height="144px" PageSize="2" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
BackColor="White" CellPadding="3" GridLines="Vertical" ForeColor="Black">
<Columns>
<GridSelectCheckBox:DGCheckBoxColumn />
</Columns>
<PagerStyle HorizontalAlign="Center" ForeColor="Black" BackColor="#999999"></PagerStyle>
</asp:DataGrid>
</form>
</body>
</HTML>
=================================
控件的源代码如下:
=================================
using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebControlLib
{
/// <summary>
/// CheckBoxColumn Derives from DataGrid Column
/// </summary>
public class DGCheckBoxColumn : DataGridColumn
{
public DGCheckBoxColumn(): base()
{
}
public override void InitializeCell(TableCell cell,
int columnIndex, ListItemType itemType)
{
//let the base class initialize the cell
base.InitializeCell(cell, columnIndex, itemType);
if( itemType == ListItemType.EditItem ||
itemType == ListItemType.Item ||
itemType == ListItemType.AlternatingItem ||
itemType == ListItemType.SelectedItem ||
itemType == ListItemType.Header)
{
CheckBox checkbox = new CheckBox();
//assign an ID that we can use to find the control later
//we don't want to add a normal checkbox to the header.
checkbox.ID = (itemType==ListItemType.Header)? "checkboxHead": "checkboxCol";
cell.Controls.Add(checkbox);
}
}
public Int32[] SelectedIndexes
{
get
{
ArrayList selectedIndexList = new ArrayList();
//iterate each DataGridItem and find our checkbox
foreach( DataGridItem item in this.Owner.Items )
{
CheckBox chkBox =
(CheckBox) item.FindControl("checkboxCol");
//If it's selected then add it to our ArrayList
if ( chkBox != null && chkBox.Checked )
{
selectedIndexList.Add( item.ItemIndex );
}
}
return (Int32[])selectedIndexList.ToArray(typeof(
System.Int32 ) );
}
}
public object[] SelectedDataKeys
{
get
{
//Just iterate each of the selectedindexes and
//match it up to the datakey field
ArrayList dataKeyList = new ArrayList();
//make sure the datakeys have some values
if(this.Owner.DataKeys.Count > 0)
{
foreach( Int32 selectedIndex in SelectedIndexes )
{
object DataKey =
(this.Owner.DataKeys[selectedIndex].ToString());
dataKeyList.Add(DataKey);
}
}
return (object[])dataKeyList.ToArray(typeof( object ) );
}
}
public static void RegisterClientCheckEvents(Page pg, string formID)
{
string strCol = GetCheckColScript();
string strHead = GetCheckHeadScript();
if(!pg.IsClientScriptBlockRegistered("clientScriptCheckAll"))
pg.RegisterClientScriptBlock("clientScriptCheckAll", strHead.Replace("[frmID]",formID));
if(!pg.IsClientScriptBlockRegistered("clientScriptCheckChanged"))
pg.RegisterClientScriptBlock("clientScriptCheckChanged", strCol.Replace("[frmID]",formID));
RegisterAttributes(pg);
}
private static void RegisterAttributes(Control ctrl)
{
foreach (Control wc in ctrl.Controls)
{
try
{
if ( wc.HasControls() )
RegisterAttributes(wc);
CheckBox chk = (CheckBox)wc;
if (chk != null && chk.ID == "checkboxCol")
{
chk.Attributes.Add("onclick","CheckChanged()");
}
else if ( chk != null && chk.ID == "checkboxHead")
{
chk.Attributes.Add("onclick","CheckAll(this)");
}
}
catch
{
}
}
}
private static string GetCheckColScript()
{
string strScript;
strScript= " <script language=JavaScript>";
strScript+=" function CheckAll( checkAllBox )";
strScript+=" {";
strScript+=" var frm = document.[frmID];";
strScript+=" var ChkState=checkAllBox.checked;";
strScript+=" for(i=0;i< frm.length;i++)";
strScript+=" {";
strScript+=" e=frm.elements[i];";
strScript+=" if(e.type=='checkbox' && e.name.indexOf('checkboxCol') != -1)";
strScript+=" e.checked= ChkState ;";
strScript+=" }";
strScript+=" }";
strScript+=" </script>";
return strScript;
}
private static string GetCheckHeadScript()
{
string strScript="";
strScript= "<script language=JavaScript>";
strScript+="function CheckChanged()";
strScript+="{";
strScript+=" var frm = document.[frmID];";
strScript+=" var boolAllChecked;";
strScript+=" boolAllChecked=true;";
strScript+=" for(i=0;i< frm.length;i++)";
strScript+=" {";
strScript+=" e=frm.elements[i];";
strScript+=" if ( e.type=='checkbox' && e.name.indexOf('checkboxCol') != -1 )";
strScript+=" if(e.checked== false)";
strScript+=" {";
strScript+=" boolAllChecked=false;";
strScript+=" break;";
strScript+=" }";
strScript+=" }";
strScript+=" for(i=0;i< frm.length;i++)";
strScript+=" {";
strScript+=" e=frm.elements[i];";
strScript+=" if ( e.type=='checkbox' && e.name.indexOf('checkboxHead') != -1 )";
strScript+=" {";
strScript+=" if( boolAllChecked==false)";
strScript+=" e.checked= false ;";
strScript+=" else";
strScript+=" e.checked= true;";
strScript+=" break;";
strScript+=" }";
strScript+=" }";
strScript+=" }";
strScript+=" </script>";
return strScript;
}
}
}