Select All rows in the DataGrid using a CheckBox

Source: Internet
Author: User

Select All rows in the DataGrid using a CheckBox

Effect Chart:

Background:

DataGrid in asp.net Select All or none of the rows in the check box

Ideas:

Because there is often this demand, the past is written on the client script, poor versatility. So I want to write this function as a control to achieve the reuse effect. Features include:

1. Placing a checkbox in the DataGrid

2, click on the column header checkbox to achieve full selection or all do not select, and the change will not be submitted to the service side, that is, no refresh phenomenon

3. Register the client's JavaScript code with static method

How to use:

Registers a tagprefix in the grid column in the. aspx file

<%@ Register tagprefix= "Gridselectcheckbox" namespace= "SolCommon.Web.UI.DataGrid"
Assembly= "projectassembly"%>

Add a selection column to the DataGrid

<asp:datagrid ...>
...
<Columns>
<gridselectcheckbox:dgcheckboxcolumn/>
...
</Columns>
...
</asp:datagrid>

Registering client code in the Page_Load method

Dgcheckboxcolumn.registerclientcheckevents (This, "Form1");

Idea: The above line must be after the DataGrid binding data, there is no error

eg

if (! Page.IsPostBack)
{
DataGrid1.DataSource = table;
Datagrid1.databind ();
}
Dgcheckboxcolumn.registerclientcheckevents (This, "Form1");

Gets the index of the rows in all selections:

Since we know so we column in the grid is the one ...
Dgcheckboxcolumn Dgchkbxcol = (dgcheckboxcolumn) mygrid.columns[0];

Iterate through the selection
foreach (int i in dgchkbxcol.selectedindexes)
{
Do something ...
}

To pay the. aspx code as follows:

<%@ 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>

=================================

The source code for the control is as follows:

=================================

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 "we can use" to "find" 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;
}
}
}
========

The first translation, the improper place a lot of include

Hope to explore together

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.