Add a CheckBox control for a DataGrid

Source: Internet
Author: User
Tags foreach count error handling eval tostring visual studio
The datagrid| control adds a CheckBox control for the DataGrid and implements the Select all feature. Here is an example of implementation

vb.net version

Checkboxdatagrid.aspx

<%@ Page language= "vb" autoeventwireup= "false" codebehind= "CheckBoxDataGrid.aspx.vb"
inherits= "Aspxweb.checkboxdatagrid"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<title> example of adding a CheckBox control for a DataGrid </title>
<meta name= "generator" content= Microsoft Visual Studio.NET 7.0 >
<meta name= "Code_language" content= "Visual Basic 7.0" >
<meta name= "vs_defaultClientScript" content= "JavaScript" >
<meta name= "vs_targetschema" content= "http://schemas.microsoft.com/intellisense/ie5" >
</HEAD>
<body ms_positioning= "GridLayout" >
<form id= "Frmmain" method= "POST" runat= "Server" >
<asp:datagrid id= "Dgmain" runat= "Server" width= "98%" autogeneratecolumns= "False" >
<selecteditemstyle font-size= "9pt" font-names= "Song Body" ></SelectedItemStyle>
<edititemstyle font-size= "9pt" font-names= "Song Body" font-bold= "True" forecolor= "Red" backcolor= "Info"/>
<alternatingitemstyle font-size= "9pt" font-names= "Song Body" forecolor= "controltext" backcolor= "white"/>
<itemstyle font-size= "9pt" font-names= "Song Body" forecolor= "Controltext" backcolor= "WhiteSmoke"/>
Verticalalign= "Middle" backcolor= "control" >
</HeaderStyle>
<Columns>
<asp:templatecolumn headertext= "Operations" >
<ItemTemplate>
<asp:checkbox id= "Chkexport" runat= "Server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:checkbox id= "Chkexporton" runat= "Server" enabled= "true"/>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:boundcolumn datafield= "id" readonly= "True" headertext= "ordinal" >
</asp:BoundColumn>
<asp:templatecolumn sortexpression= "Demo" headertext= "title" >
<ItemTemplate>
<asp:label text= ' <%# server.htmlencode (DataBinder.Eval (Container.DataItem, "Title"))%> '
runat= "Server" width= "80%" id= "Lblcolumn"/>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:button id= "Cmdselectall" runat= "Server" text= "All selected" ></asp:Button>
<asp:button id= "cmdfindselected" runat= "Server" text= "View selected items" ></asp:Button>
<br>
<asp:label id= "Label1" runat= "Server" ></asp:Label>
</form>
</body>
</HTML>

Post Code CheckBoxDataGrid.aspx.vb

Imports System.Data
Imports System.Data.OleDb

Public Class Checkboxdatagrid
Inherits System.Web.UI.Page
Protected WithEvents Cmdselectall as System.Web.UI.WebControls.Button
Protected WithEvents Dgmain as System.Web.UI.WebControls.DataGrid
Protected WithEvents cmdfindselected as System.Web.UI.WebControls.Button

Dim oDataView as DataView
Protected WithEvents Label1 as System.Web.UI.WebControls.Label
Dim sConnectionString as String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
+ Server.MapPath ("Test.mdb")


#Region "Web Form Designer generated Code"

' This are required by the Web Form Designer.
<system.diagnostics.debuggerstepthrough () > Private Sub InitializeComponent ()

End Sub

Private Sub Page_Init (ByVal sender as System.Object, ByVal e as System.EventArgs) _
Handles Mybase.init
' Codegen:this Method-required by the Web Form Designer
' Do not modify it using the ' Code Editor.
InitializeComponent ()
End Sub

#End Region

Private Sub Page_Load (ByVal sender as System.Object, ByVal e as System.EventArgs) _
Handles MyBase.Load
' Put user code to initialize the page
Dgmain.columns (0). HeaderText = "Options"
Dgmain.columns (1). HeaderText = "ordinal"
Dgmain.columns (2). HeaderText = "title"
Cmdfindselected.text = "View Selected items"
Refreshgrid ()
If not Page.IsPostBack Then
Cmdselectall.text = "All selected"
Dgmain.databind ()
End If

End Sub


#Region "Process multiple selections"
Private Sub Cmdselectall_click (ByVal sender as System.Object, ByVal e as System.EventArgs) _
Handles Cmdselectall.click
SelectAll ()
End Sub

Private Sub SelectAll ()
Dim Odatagriditem as DataGridItem
Dim Chkexport as System.Web.UI.WebControls.CheckBox

If Cmdselectall.text = "All selected" Then
For each odatagriditem in Dgmain.items
Chkexport = Odatagriditem.findcontrol ("Chkexport")
chkexport.checked = True
Next
Cmdselectall.text = "All not selected"
Else
For each odatagriditem in Dgmain.items
Chkexport = Odatagriditem.findcontrol ("Chkexport")
chkexport.checked = False
Next
Cmdselectall.text = "All selected"
End If
End Sub
#End Region

#Region "Update DataGrid"

Private Sub Refreshgrid ()
Dim Oconnection as OleDbConnection
Dim Ocommand as OleDbDataAdapter
Dim Odataset as New DataSet ()

Try
Dim sSQL as String = "Select Top 5 * out testtable ORDER by id"
oconnection = New OleDbConnection (sConnectionString)
Ocommand = New OleDbDataAdapter (ssql.tostring, oconnection)
Ocommand.fill (Odataset, "TestTable")
oDataView = New DataView (odataset.tables ("TestTable"))
Dgmain.datasource = oDataView
Oconnection.close ()

Catch ex as Exception
'//Place Error handling
End Try
End Sub
#End Region

Private Sub Cmdfindselected_click (ByVal sender as System.Object, ByVal e as System.EventArgs) _
Handles Cmdfindselected.click
Dim Odatagriditem as DataGridItem
Dim Chkexport as System.Web.UI.WebControls.CheckBox
Dim Oexargs as New System.Collections.ArrayList ()
Dim SID as String
Label1.Text = ""
For each odatagriditem in Dgmain.items
Chkexport = Odatagriditem.findcontrol ("Chkexport")
If chkexport.checked Then
Label1.Text = ""
SID = CType (Odatagriditem.findcontrol ("Lblcolumn"), Label). Text
Oexargs.add (SID)
Dim i as Integer = 0
For i = 0 to Oexargs.count-1
Label1.Text + = Oexargs (i) + ","
Next
End If
Next
End Sub

End Class

C # version

Checkboxdatagrid.aspx

<%@ Page language= "C #" EnableViewState = "true" codebehind= "DataGridCheckBox.aspx.cs"
Autoeventwireup= "false" inherits= "EMeng.Exam.DataGridCheckBox.DataGridCheckBox"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<title> example of adding a CheckBox control for a DataGrid </title>
</HEAD>
<body>
<form id= "Frmmain" method= "POST" runat= "Server" >
<asp:datagrid id= "Dgmain" runat= "Server" width= "98%" autogeneratecolumns= "False" font-size= "9pt" font-names= "Song Body" >
<alternatingitemstyle forecolor= "Controltext" backcolor= "white"/>
<itemstyle forecolor= "Controltext" backcolor= "WhiteSmoke"/>
Backcolor= "Control" ></HeaderStyle>
<Columns>
<asp:templatecolumn headertext= "Operations" >
<ItemTemplate>
<input type= "hidden" id= "Selectedid" runat= "Server"
Value= ' <%# DataBinder.Eval (Container.DataItem, "id")%> '/>
<asp:checkbox id= "Chkexport" runat= "Server"/>
</ItemTemplate>
</asp:TemplateColumn>
<asp:boundcolumn datafield= "id" readonly= "True" headertext= "ordinal" >
</asp:BoundColumn>
<asp:templatecolumn sortexpression= "Demo" headertext= "title" >
<ItemTemplate>
<asp:label text= ' <%# Server.HTMLEncode ((String) DataBinder.Eval (Container.DataItem, "Title"))%> '
runat= "Server" width= "80%" id= "Lblcolumn"/>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:button id= "Cmdselectall" runat= "Server" text= "All selected" ></asp:Button>
<asp:button id= "cmdfindselected" runat= "Server" text= "View selected items" ></asp:Button>
<br>
<asp:label id= "Label1" runat= "Server" ></asp:Label>
<asp:label id= "Label2" runat= "Server" ></asp:Label>
</form>
</body>
</HTML>

DataGridCheckBox.aspx.cs

Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Data.OleDb;
Using System.Drawing;
Using System.Web;
Using System.Web.SessionState;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;

Namespace EMeng.Exam.DataGridCheckBox
{
<summary>
Summary description of the Datagridcheckbox.
"The Wonderful World of Mengxian"
</summary>
public class DataGridCheckBox:System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Cmdselectall;
protected System.Web.UI.WebControls.Button cmdfindselected;
protected System.Web.UI.WebControls.DataGrid Dgmain;
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Label Label2;
DataView oDataView;
string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source="
+ HttpContext.Current.Server.MapPath (".. /.. /aspxweb.mdb.ascx ");

private void Page_Load (object sender, System.EventArgs e)
{
Place user code here to initialize page
Dgmain.columns[0]. HeaderText = "option";
DGMAIN.COLUMNS[1]. HeaderText = "serial number";
DGMAIN.COLUMNS[2]. HeaderText = "title";
Cmdfindselected.text = "View selected items";
Refreshgrid ();
if (!this. IsPostBack)
{
Cmdselectall.text = "All selected";
Dgmain.databind ();
}
}
#region Web Form Designer generated code
Override protected void OnInit (EventArgs e)
{
//
CodeGen: This call is required for the ASP.net Web forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</summary>
private void InitializeComponent ()
{
This.cmdSelectAll.Click + = new System.EventHandler (This.cmdselectall_click);
This.cmdFindSelected.Click + = new System.EventHandler (This.cmdfindselected_click);
This. Load + = new System.EventHandler (this. Page_Load);

}
#endregion

private void Cmdselectall_click (object sender, System.EventArgs e)
{
SelectAll ();
}

private void SelectAll ()
{
System.Web.UI.WebControls.CheckBox Chkexport;
if (Cmdselectall.text = = "All selected")
{
foreach (DataGridItem odatagriditem in Dgmain.items)
{
Chkexport = (checkbox) Odatagriditem.findcontrol ("Chkexport");
Chkexport.checked = true;
}
Cmdselectall.text = "All do not choose";
}
Else
{
foreach (DataGridItem odatagriditem in Dgmain.items)
{
Chkexport = (checkbox) Odatagriditem.findcontrol ("Chkexport");
chkexport.checked = false;
}
Cmdselectall.text = "All selected";
}
}

private void Refreshgrid ()
{
OleDbConnection oconnection;
OleDbDataAdapter Ocommand;
DataSet Odataset = new DataSet ();
Try
{
string sSQL = "SELECT top * from Document ORDER by CreateDate DESC";
oconnection = new OleDbConnection (sConnectionString);
Ocommand = new OleDbDataAdapter (ssql.tostring (), oconnection);
Ocommand.fill (Odataset, "Document");
oDataView = new DataView (odataset.tables["Document");
Dgmain.datasource = oDataView;
Oconnection.close ();
}
catch (Exception ex)
{
Label1.Text = ex. Message.tostring ();
}
}

private void Cmdfindselected_click (object sender, System.EventArgs e)
{
System.Web.UI.WebControls.CheckBox Chkexport;
System.Collections.ArrayList Oexargs = new System.Collections.ArrayList ();
String SID;
Label1.Text = "";
Label2.Text = "";
foreach (DataGridItem odatagriditem in Dgmain.items)
{
Chkexport = (checkbox) Odatagriditem.findcontrol ("Chkexport");
if (chkexport.checked)
{
If you want to delete, you can construct the SQL statement here to delete
String sql = "DELETE from Document WHERE id ="
+ ((HtmlInputHidden) Odatagriditem.findcontrol ("Selectedid")). Value;
Label2.Text + + "<li>" + SQL;
SID = ((HtmlInputHidden) Odatagriditem.findcontrol ("Selectedid")). Value;
Oexargs.add (SID);
int i = 0;
Label1.Text = "";
for (i = 0;i<oexargs.count;i++)
{
Label1.Text + + oexargs[i] + "<br>";
}
}
}
Label2.Text = "<br><font color=red> Execute SQL statement can be deleted, here omitted. </font> ";
}
}
}



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.