Create multiple links and checkbox event responses in a DataGrid with code

Source: Internet
Author: User
Tags sort tostring trim
datagrid| Create | link | response

This example uses code to create a DataGrid and respond to a checkbox event, and implements the multivariable transfer of a hyperlink column.

Create a front page

Createdatagrid.aspx:

Add a plcaeholder,id to the form "ph", runat= "Server"

Background page

CreateDatagrid.aspx.cs

public class CreateDataGrid:System.Web.UI.Page
{
public String sql = ' Select firstname,lastname,homephone,title from Employees ';
Public DataGrid Mygrid = new DataGrid ();
protected System.Web.UI.WebControls.PlaceHolder ph;
Public String SortExpression;
private void Page_Load (object sender, System.EventArgs e)
{
CREATEDATAGRIDFORM.CONTROLS.ADD (Makegrid ());

THIS.PH.CONTROLS.ADD (Makegrid ());
}
protected override void CreateChildControls ()
//        {

Base. CreateChildControls ();
//}

Code generated #region the Web forms Designer
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. Load + = new System.EventHandler (this. Page_Load);

}
#endregion
<summary>
Create a template column and a column template
</summary>

Public TemplateColumn TM = new TemplateColumn ();
Public Columntemplate MyCol = new Columntemplate ();

Back to DataView
Public DataView CreateDataSource ()
{
String strSQL;
strSQL = "Data source=localhost;initial catalog=northwind; User Id=sa; Password=sa; ";
SqlConnection conn = new SqlConnection (strSQL);
SqlDataAdapter db_sqladaptor = new SqlDataAdapter (Sql,conn);
DataSet ds = new DataSet ();
Db_sqladaptor. Fill (ds, "Employees");
DataView MyView = ds. tables["Employees"]. DefaultView;
Myview.sort=sortexpression;
Response.Write (SQL);
return myview;
}

<summary>
Handling sorting
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
public void Sort_grid (Object sender, DataGridSortCommandEventArgs e)
{
SortExpression = E.sortexpression.tostring ();
session["SortField"]=sortexpression.trim ();
if (session["order"]==null) session["Order" = "ASC";
session["Order" = (session["order"). ToString () = = "DESC")? ASC ":" "DESC";
if (session["SortField"]==null) session["SortField"] = "FirstName";
SQL + = "ORDER By" +session["SortField"]. ToString () + "" + session["order"]. ToString ();
Mygrid. DataSource = CreateDataSource ();
Mygrid. DataBind ();
}
<summary>
Creates and sets the DataGrid property, where the property is set to a fixed value, but can also be set dynamically
</summary>
<returns></returns>

Public DataGrid Makegrid ()
{
Mygrid. cellpadding=2;
Mygrid. Attributes.Add ("Align", "center");
Mygrid. cellspacing=0;
Mygrid. width=500;
Mygrid. borderwidth=1;
Mygrid. Bordercolor=colortranslator.fromhtml ("Black");
Mygrid. Autogeneratecolumns=false;
Mygrid. Forecolor=colortranslator.fromhtml ("Black");
Mygrid. font.size=9;
Mygrid. Font.name= "Song Body";
Mygrid. Allowsorting=true;

Event handler for sort command

Mygrid. SortCommand + = new Datagridsortcommandeventhandler (Sort_grid);
Mygrid. ItemDataBound +=new Datagriditemeventhandler (mygrid_itemdatabound);

           ///settings HeaderStyle
             Mygrid. Headerstyle.backcolor=colortranslator.fromhtml ("Gold");
            Mygrid. Headerstyle.forecolor=colortranslator.fromhtml ("Black");
            Mygrid. Headerstyle.font.name= "Song Body";
            Mygrid. headerstyle.font.size=9;
            Mygrid. Headerstyle.font.bold=true;
            Mygrid. Headerstyle.horizontalalign=horizontalalign.center;

Set alternating style
Mygrid. Alternatingitemstyle.backcolor=colortranslator.fromhtml ("Silver");
Mygrid. Alternatingitemstyle.forecolor=colortranslator.fromhtml ("Black");

Set ItemStyle
Mygrid. Itemstyle.horizontalalign=horizontalalign.left;

To create bound columns and properties

HyperLinkColumn FirstName = new HyperLinkColumn ();
BoundColumn LastName = new BoundColumn ();
BoundColumn homephone = new BoundColumn ();
BoundColumn Title = new BoundColumn ();

firstname.headertext= "Name";
Firstname.datafield= "FirstName";
Firstname.sortexpression= "FirstName";

firstname.headertext= "Name";

Firstname.datatextfield = "FirstName";
Firstname.sortexpression= "FirstName";
Firstname.navigateurl = "http://localhost/test.aspx";

lastname.headertext= "Surname";
Lastname.datafield= "LastName";
Lastname.sortexpression= "LastName";

homephone.headertext= "Telephone";
Homephone.datafield= "HomePhone";
Homephone.sortexpression= "HomePhone";

title.headertext= "position";
Title.datafield= "Title";
Title.sortexpression= "Title";

            Mygrid. Columns.addat (0, FirstName);
            Mygrid. Columns.addat (1, LastName);
            Mygrid. Columns.addat (2, HomePhone);
            Mygrid. Columns.addat (3, Title);

Set up template column properties and ItemStyle templates
Tm. headertext= "* * Delete information * *";
Tm. Headerstyle.horizontalalign=horizontalalign.center;
Tm. Itemstyle.backcolor = colortranslator.fromhtml ("#FFF778");
Tm. Itemstyle.horizontalalign=horizontalalign.center;

TemplateColumn aa=new TemplateColumn ();
ColumnTemplate1 tt = new ColumnTemplate1 ();
Aa. ItemTemplate = TT;


Create a column template.
Column templates inherit from ITemplate
Tm. ItemTemplate = MyCol;
Mygrid. Columns.addat (4, TM);
Mygrid. Columns.addat (5,AA);

Binding and returning
Mygrid. DataSource = CreateDataSource ();
Mygrid. DataBind ();
return mygrid;
}

private void Mygrid_itemdatabound (object sender, DataGridItemEventArgs e)
{
if (E.item.itemtype = = ListItemType.Item | | e.item.itemtype = = listitemtype.alternatingitem)
{
HyperLink link = (HyperLink) e.item.cells[0]. Controls[0];
String url = link. NavigateUrl;
Implementing multiple Parameter Links
url = "? id=" + e.item.cells[1]. Text + "&id2=" + e.item.cells[2]. Text;
Link. NavigateUrl = URL;
}
}
}


add a few more critical segments

Columntemplate inherits from ITemplate.
"InstantiateIn" defines who the child controls belong to

public class Columntemplate:itemplate
{

public void InstantiateIn (Control container)
{
Label MyLabel = new label ();
mylabel.text= "click Delete";
CheckBox MyCheckBox = new checkbox ();
Container. Controls.Add (MyLabel);
Container. Controls.Add (MyCheckBox);
}

}

To add a CheckBox event:

public class Columntemplate1:itemplate
{

public void InstantiateIn (Control container)
{
Label MyLabel = new label ();
mylabel.text= "Test";
CheckBox lnk = new checkbox ();
Lnk. AutoPostBack = true;
Lnk. CheckedChanged +=new EventHandler (lnk_checkedchanged);
Container. Controls.Add (MyLabel);
Container. Controls.Add (LNK);
}


private void Lnk_checkedchanged (object sender, EventArgs e)
{
CheckBox lnk = (checkbox) sender;
DataGrid dg = (DataGrid) lnk. Namingcontainer.namingcontainer;
if (DG = null) return;
Implementing a CheckBox Event response
DataGridItem di = (DataGridItem) lnk. NamingContainer;
HyperLink lnkid= (HyperLink) di. Cells[0]. Controls[0];
String s2 = LnkID.Text.Trim () +lnk.id+ "was selected!" ";
}
}



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.