Use checkbox to select all rows in the DataGrid

Source: Internet
Author: User

Use checkbox to select all rows in the DataGrid

:

Background:

In Asp.net, use the check box to select all or no rows in the DataGrid.

Ideas:

Because this demand often exists, scripts are written on the client in the past, and the versatility is poor. So I want to write this function as a control for reuse. Features:

1. Place checkbox in the DataGrid

2. Click the checkbox in the column header to select all or not select all, and the change will not be submitted to the server, that is, there is no refresh.

3. Use static methods to register the JavaScript code of the client.

How to use:

Register a tagprefix in the grid column in The. aspx file.

<% @ Register tagprefix = "gridselectcheckbox" namespace = "solcommon. Web. UI. DataGrid"
Assembly = "projectassembly" %>

Add select columns to the DataGrid

<Asp: DataGrid...>
...
<Columns>
<Gridselectcheckbox: dgcheckboxcolumn/>
...
</Columns>
...
</ASP: DataGrid>

Register the client code in the page_load Method

Dgcheckboxcolumn. registerclientcheckevents (this, "form1 ");

// Idea: The above row must be bound to the data in the DataGrid without errors

Eg:

If (! Page. ispostback)
{
Datagrid1.datasource = table;
Datagrid1.databind ();
}
Dgcheckboxcolumn. registerclientcheckevents (this, "form1 ");

Obtain the index of all selected rows:

// 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...
}

The code for Fu. aspx is 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 of 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 = 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 (maid 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, many of which are inappropriate

Hope to discuss it 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.