Asp. A brief introduction to the application techniques of DataGrid control in net

Source: Internet
Author: User
Tags bind eval generator modify first row visual studio
Asp.net|datagrid|datagrid Control | tips one. Overview:

In the process of developing a Web application using ASP.net, the DataGrid is a very important control, and almost any data-related performance needs to be used for that control. So mastering the application skills of the DataGrid control is essential to every web developer.

The DataGrid control can dramatically simplify the development of Web applications by displaying data from a data source in a tabular format and providing some powerful built-in features such as paging, sorting, and filtering. At the same time, developers can use a variety of data binding columns to customize how the DataGrid control displays data, which greatly enhances the functionality of the DataGrid control. This article I will introduce to you how to use the TemplateColumn, EditCommandColumn, HyperLinkColumn, ButtonColumn and BoundColumn, and so on, customize how the DataGrid control displays data.

   two. Application of BoundColumn data columns:

Generally, when we use the DataGrid control to develop a data-driven Web application, a single record in the data source is displayed in one row, while one of the columns displays a specific field value. The DataGrid control itself provides us with powerful capabilities, so we need to be able to display the data with very little code. However, this also poses a problem, that is, how do we personalize the way the data is displayed? Obviously DataList controls and repeater controls are better at this than the DataGrid controls, but if we give up the DataGrid control it is equivalent to giving up the power that it has. So how do we use the DataGrid control to implement the custom features of data display? First, we turn off the DataGrid control by automatically generating data-bound columns from the data source, simply by setting its AutoGenerateColumns property to False. Here is an example of this approach:

<asp:datagrid runat= "Server" id= "Mydatagrid" autogeneratecolumns= "False"
</asp:DataGrid>

Once its AutoGenerateColumns property is false, we have to programmatically implement the binding of the data column. In the process of binding a data column, we can use any of the V data columns described above, but any data column must be defined within the <Columns> </Columns> tag, which indicates that the object being defined is a data column.

Let's first introduce the application of BoundColumn data columns. By using BoundColumn data columns, we can dynamically bind data from a data source to a specific data column and modify the appearance of the data column to suit our needs, such as changing the order in which columns are displayed, and allowing the DataGrid control to display only the values of certain fields, not the values of all fields, Change the title of the data column, and so on. BoundColumn data columns can set properties such as DataField, DataFormatString, Footertext, HeaderText, Headerimageurl, and SortField. And that's what makes the DataGrid control look so changeable and colourful.

Next, we build an example Web application project that works with the DataGrid control and shows how to use BoundColumn data columns to customize how data is displayed. The following is the main file for this project and the contents of its code-behind file:

WebForm1.aspx:

<%@ Page language= "C #" codebehind= "WebForm1.aspx.cs" autoeventwireup= "false" inherits= "Datagridtemplates.webform1"% >
! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en"
<HTML>
<HEAD>
<title> WebForm1 </title>
<meta name= "generator" content= "Microsoft Visual Studio 7.0"
<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>
<form id= "Form1" method= "POST" runat= "Server"
<asp:datagrid runat= "Server" id= "Mydatagrid" autogeneratecolumns= "False" borderwidth= "1px" font-names= "Verdana, Arial,sans-serif "font-size=" 12px "bordercolor=" #404040 "gridlines=" Horizontal "cellpadding=" 4 "
<alternatingitemstyle backcolor= "#E0E0E0" > </AlternatingItemStyle>
<Columns>
<asp:boundcolumn datafield= "CustomerID" headertext= "ID" > </asp:BoundColumn>
<asp:boundcolumn datafield= "CompanyName" headertext= "Company Name" > </asp:BoundColumn>
<asp:boundcolumn datafield= "ContactName" headertext= "Contact Name" > </asp:BoundColumn>
<asp:boundcolumn datafield= "Address" headertext= "address" > </asp:BoundColumn>
<asp:boundcolumn datafield= "City" headertext= "City" > </asp:BoundColumn>
<asp:boundcolumn datafield= "Region" headertext= "Region" > </asp:BoundColumn>
<asp:boundcolumn datafield= "PostalCode" headertext= "Postal Code"
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
</form>
</body>
</HTML>

WebForm1.aspx.cs:
Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Data.SqlClient;
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 Datagridtemplates
{


Summary description of the WebForm1.

public class WebForm1:System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid Mydatagrid;

private void Page_Load (object sender, System.EventArgs e)
{
Place user code here to initialize page
if (! Page.IsPostBack)
Binddata ();
}

private void Binddata ()
{
SqlConnection con = new SqlConnection ("server=localhost;database=northwind;integrated security=true;");
SqlCommand cmd = new SqlCommand ("SELECT * from Customers", con);

Try
{
Con. Open ();
Mydatagrid.datasource = cmd. ExecuteReader ();
Mydatagrid.databind ();
Con. Close ();
}
catch (Exception) {}
if (con!= null && con. state = = ConnectionState.Open)
Con. Close ();
}

#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);
}


Designer supports required methods-do not use the Code editor to modify
The contents of this method.

private void InitializeComponent ()
{
This. Load + = new System.EventHandler (this. Page_Load);
}
#endregion
}
}

When the project is created, the effect that runs in the browser is as shown in Figure 1:


Figure 1 The effect of using BoundColumn data columns to display data in the DataGrid control.

  three. HyperLinkColumn data columns and the use of ButtonColumn data columns:

I've introduced the application of BoundColumn data columns, while the other two data columns: HyperLinkColumn data columns and buttoncolumn data columns are applied in the same way.

The HyperLinkColumn data column contains the DataTextField property and the Datanavigateurlfield property, which can be used to specify the text content to display, and the latter to specify the hyperlink. The HyperLinkColumn data column also contains a datanavigateurlformatstring property that can be used to specify the text display format.

ButtonColumn data columns, like HyperLinkColumn data columns, also provide DataTextField properties as well as datatextformatstring properties. It also provides a CommandName property that specifies the response action on the server side when the button is clicked. At this point, the OnItemCommand property of the DataGrid control must point to a corresponding method that is automatically invoked when the button is clicked. A row in the DataGrid control can contain multiple ButtonColumn data columns, and the button message response function in each data column is the method corresponding to the OnItemCommand property. The different buttons are based on their commandname properties to differentiate between the different parts of the function that should be performed. The ButtonColumn data column also provides a ButtonType property to specify the appearance of the button, which includes two desirable values: LinkButton (default) and Pushbutton.

Next, we add a new Web application project based on the original solution and use the DataGrid control's BoundColumn data columns, hyperlinkcolumn data columns, and buttoncolumn data columns. The following is the main file for this project and the contents of its code-behind file:

WebForm1.aspx:

<%@ Page language= "C #" codebehind= "WebForm1.aspx.cs" autoeventwireup= "false" inherits= "Datagridtemplates2.webform1" %>
! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en"
<HTML>
<HEAD>
<title> WebForm1 </title>
<meta name= "generator" content= "Microsoft Visual Studio 7.0"
<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= "FlowLayout"
<form id= "Form1" method= "POST" runat= "Server"
<asp:datagrid id= "Mydatagrid" runat= "Server" headerstyle-font-bold= "True" cellpadding= "4" borderwidth= "1px" autogeneratecolumns= "False" gridlines= "horizontal" font-names= "Verdana,arial,sans-serif" Font-Size= "12px" Borderstyle= "Solid" >
<alternatingitemstyle backcolor= "#EFEFEF" > </AlternatingItemStyle>
<itemstyle font-size= "X-small" > </ItemStyle>
<Columns>
<asp:boundcolumn datafield= "CustomerID" headertext= "ID" > </asp:BoundColumn>
<asp:hyperlinkcolumn datanavigateurlfield= "Url" datatextfield= "CompanyName" headertext= "Comapny Name" ></asp: hyperlinkcolumn>
<asp:buttoncolumn text= "Get Details" buttontype= "pushbutton" Commandname= "getdetails" > </asp:ButtonColumn>
</Columns>
</asp:DataGrid>
</form>
</body>
</HTML>

WebForm1.aspx.cs:
Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Data.SqlClient;
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 DataGridTemplates2
{


Summary description of the WebForm1.

public class WebForm1:System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid Mydatagrid;

private void Page_Load (object sender, System.EventArgs e)
{
Place user code here to initialize page
if (! Page.IsPostBack)
Binddata ();
}

private void Binddata ()
{
SqlConnection con = new SqlConnection ("server=localhost;integrated security=true; Database=northwind ");
SqlCommand cmd = new SqlCommand ("SELECT *, ' http://www. ' + CustomerID + '. com ' as Url from Customers", con);
Try
{
Con. Open ();
Mydatagrid.datasource = cmd. ExecuteReader ();
Mydatagrid.databind ();
Con. Close ();
}
catch (Exception) {}
if (con!= null && con. state = = ConnectionState.Open)
Con. Close ();
}

#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);
}


Designer supports required methods-do not use the Code editor to modify
The contents of this method.

private void InitializeComponent ()
{
This.myDataGrid.ItemCommand + = new System.Web.UI.WebControls.DataGridCommandEventHandler (this.mydatagrid_ ItemCommand);
This. Load + = new System.EventHandler (this. Page_Load);
}
#endregion

private void Mydatagrid_itemcommand (object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (E.commandname = = "Getdetails")
Response.Redirect ("webform2.aspx?id=" + e.item.cells[0]. Text);
}
}
}

When the project is created, the effect that runs in the browser is as shown in Figure 2:


Figure 2 The effect of using HyperLinkColumn and ButtonColumn data columns to display data in the DataGrid control.

  Four. Application of TemplateColumn data columns:

The TemplateColumn data column in the DataGrid control can be said to be extremely powerful, and using it flexibly allows the DataGrid control to display data in a variety of ways. The TemplateColumn data column provides us with the following four types of data column templates:

· HeaderTemplate
· ItemTemplate
· EditItemTemplate
· FooterTemplate

Where HeaderTemplate is used to display text, pictures, or bound data in the first row of the DataGrid control. The FooterTemplate function is similar to the HeaderTemplate function, but it is used to display the contents of the tail line. EditItemTemplate is applied to data columns with editing capabilities, and any data columns that use the template can be edited by the user and updated to the data source in due course.

ItemTemplate allows you to create data columns with fully customizable data display. By using <%# Container.DataItem ("[FieldName]")% or <%# DataBinder.Eval (Container.DataItem, "[FieldName]", "{0:[ FormatString]} ")%> two data-binding syntax You can bind a column of data from a data source to the corresponding data column and give the fully customizable display.

Here we add a new Web page-webform2 to the Web application created in step three, which shows the company details, which is the page that the browser will guide when the button in Figure 2 is clicked. It can display the detailed information of the company according to the user's choice, the method is to judge the information within the request.querystring. If it contains an "id" name/value pair, the corresponding company information is selected according to its value and displayed in the page, and all company information is selected from the datasheet and displayed on the page if there is no information containing any "id" value. Also note that in a DataGrid control you can combine multiple types of data columns and select the appropriate data columns to display the corresponding data according to different needs. The following is the HTML file for this page and the contents of its code-behind file:

Webform2.aspx:

<%@ Page language= "C #" codebehind= "WebForm2.aspx.cs" autoeventwireup= "false" inherits= "Datagridtemplates2.webform2" %>
! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en"
<HTML>
<HEAD>
<title> WebForm2 </title>
<meta name= "generator" content= "Microsoft Visual Studio 7.0"
<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= "FlowLayout"
<form id= "Form1" method= "POST" runat= "Server"
<asp:datagrid id= "Mydatagrid" runat= "Server" itemstyle-font-size= "X-small" headerstyle-font-bold= "True" Headerstyle-font-size= "X-small" alternatingitemstyle-backcolor= "#EFEFEF" cellpadding= "4" borderwidth= "1" autogeneratecolumns= "False" borderstyle= "Solid" gridlines= Horizontal "bordercolor=" #404040 "font-names=" Verdana, Arial,sans-serif "font-size=" 11px ">
<alternatingitemstyle backcolor= "#E0E0E0" > </AlternatingItemStyle>
<itemstyle font-size= "X-small" > </ItemStyle>
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<b> Company Detail </b>
</HeaderTemplate>
<ItemTemplate>
<table border= "0" cellpadding= "4" cellspacing= "0" width= "100%" style= "font-size:11px"; Font-family:verdana, Arial, Sans-serif ">
<tr>
<TD colspan= "4" >
<b>
<%# DataBinder.Eval (Container.DataItem, "CompanyName")%>
</b>
</td>
</tr>
<tr>
<TD width= "25%" valign= "top" > <b> Contacts: </b> </td>
<TD width= "25%" valign= "Top" nowrap>
<%# DataBinder.Eval (Container.DataItem, "ContactName")%>
</td>
<TD width= "25%" valign= "top" > <b> Phone: </b> </td>
<TD width= "25%" valign= "Top" nowrap>
<%# DataBinder.Eval (Container.DataItem, "Phone")%>
</td>
</tr>
<tr>
<TD width= "25%" valign= "top" > <b> Title: </b> </td>
<TD width= "25%" valign= "Top"
<%# DataBinder.Eval (Container.DataItem, "ContactTitle")%>
</td>
<TD width= "25%" valign= "top" > <b> Fax: </b> </td>
<TD width= "25%" valign= "Top" nowrap>
<%# DataBinder.Eval (Container.DataItem, "Fax")%>
</td>
</tr>
<tr>
<TD width= "25%" valign= "top" and <b> Address: </b> </td>
<TD width= "25%" valign= "Top" colspan= "3"
<%# DataBinder.Eval (Container.DataItem, "address")%>
<br>
<%# DataBinder.Eval (Container.DataItem, "City")%>
,
<%# DataBinder.Eval (Container.DataItem, "Region")%>
<%# DataBinder.Eval (Container.DataItem, "PostalCode")%>
<br>
<%# DataBinder.Eval (Container.DataItem, "Country")%>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
</form>
</body>
</HTML>

WebForm2.aspx.cs:
Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Data.SqlClient;
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 DataGridTemplates2
{


Summary description of the WebForm2.

public class WebForm2:System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid Mydatagrid;

private void Page_Load (object sender, System.EventArgs e)
{
Place user code here to initialize page
if (! Page.IsPostBack)
Binddata ();
}

private void Binddata ()
{
DataSet ds = new DataSet ();
SqlDataAdapter da;
String strSQL;

if (request.querystring["id"] = = null)
strSQL = "SELECT * from Customers";
Else
strSQL = "SELECT * from Customers WHERE CustomerID = '" + request.querystring["id"]. ToString () + "'";

da = new SqlDataAdapter (strSQL, "server=localhost;integrated security=true;database=northwind");
Da. Fill (ds, "Customers");
Mydatagrid.datasource = ds. tables["Customers"]. DefaultView;
Mydatagrid.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);
}


Designer supports required methods-do not use the Code editor to modify
The contents of this method.

private void InitializeComponent ()
{
This. Load + = new System.EventHandler (this. Page_Load);
}
#endregion
}
}

When the new page is created, the effect that runs in the browser is shown in Figure 3:


Figure 3 The effect of using TemplateColumn data columns to display data in the DataGrid control.

  Five Summarize:

So far, I think you've got a pretty good grip on how to use the DataGrid control to customize the data display in a Web application. The DataGrid control has more powerful features than DataList controls and repeater controls, and its custom data display is not weak. So as long as you have a good grasp of the skills and methods, the use of the DataGrid control can also make your Web application not only powerful data processing capabilities, and very rich personality.



Related Article

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.