Advanced Techniques of the gridview control in ASP. NET 2.0

Source: Internet
Author: User

In ASP. NET 2.0, the newly added gridview control is indeed very powerful, making up for the shortcomings when using the DataGrid Control in Asp.net 1.1. In Asp.net 1.1, when using DataGrid, a lot of code is still required in many cases, which is inconvenient and sometimes requires a lot of skills. In Asp.net 2.0, when using the gridview control, you even need to drag the control and set properties without writing any code. Use ASP. NET 2.0 and ASP. in net2.0 using the gridview control to operate data, a series of introductions have been made to the gridview control. If you have never understood the gridview before, read these two articles first. In this article, I will continue to introduce some of the usage skills of the gridview.

  1. format the gridview

Like Asp.net 1.1, gridview can easily customize its style, such as CSS and color. To customize the format of the gridview, you only need to right-click the gridview and select "auto format" in the pop-up menu. You can select the gridview style with many built-in styles, for example:

If you want to customize the format of each column in The gridview, you only need to click "Smart Tag" in the upper-right corner of the gridview. In the pop-up menu, select "Edit columns ", A form such as is displayed, so that you can set each column in detail:
  

For example, if you want to set a column to a special format, to set unitprice to a currency format, you can set it to {0: c} in the dataformatstring attribute of the unitprice column }, the program code is as follows:

<% @ Page Language = "C #" %>
<! Doctype HTML public "-// W3C // dtd xhtml 1.1 // en"
Http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd>
<SCRIPT runat = "server">
</SCRIPT>
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> untitled page </title>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Asp: sqldatasource id = "productsdatasource"
Runat = "server"
Selectcommand = "select [productid], [productname],
[Quantityperunit], [unitprice], [unitsinstock] From
[Products]"
Connectionstring = "<% $ connectionstrings: nwconnectionstring %>"
Performancemode = "datareader">
</ASP: sqldatasource>
<Asp: gridview id = "productgridview" runat = "server"
Performanceid = "productsdatasource"
Datakeynames = "productid" autogeneratecolumns = "false"
Borderwidth = "1px" backcolor = "# deba84"
Cellpadding = "3" cellspacing = "2" borderstyle = "NONE"
Bordercolor = "# deba84">
<Footerstyle forecolor = "#8c4510" backcolor = "# f7dfb5"> </footerstyle>
<Pagerstyle forecolor = "#8c4510" horizontalalign = "center"> </pagerstyle>
<Headerstyle forecolor = "white" font-bold = "true" backcolor = "# a55129">
<Columns>
<Asp: boundfield readonly = "true" headertext = "ID" insertvisible = "false" datafield = "productid"
Sortexpression = "productid">
<Itemstyle horizontalalign = "center"> </itemstyle>
</ASP: boundfield>
<Asp: boundfield headertext = "name" datafield = "productname" sortexpression = "productname">
</ASP: boundfield>
<Asp: boundfield headertext = "qty/unit"
Datafield = "quantityperunit"
Sortexpression = "quantityperunit"> </ASP: boundfield>
<Asp: boundfield headertext = "price/unit"
Datafield = "unitprice" sortexpression = "unitprice"
Dataformatstring = "{0: c}">
<Itemstyle horizontalalign = "right"> </itemstyle>
</ASP: boundfield>
<Asp: boundfield headertext = "units in stock" datafield = "unitsinstock"
Sortexpression = "unitsinstock"
Dataformatstring = "{0: d}">
<Itemstyle horizontalalign = "right"> </itemstyle>
</ASP: boundfield>
</Columns>
<Selectedrowstyle forecolor = "white" font-bold = "true"
Backcolor = "# 738a9c"> </selectedrowstyle>
<Rowstyle forecolor = "#8c4510" backcolor = "# fff7e7"> </rowstyle>
</ASP: gridview>
</Div>
</Form>
</Body>
</Html>

The result is as follows:

In some cases, we may need to display the data in the gridview as needed. For example, when the inventory of a certain item is 0, the gridview must be displayed in different colors, you can do this as follows:

First, the gridview provides the rowdatabound event, which is triggered after each row in the gridview is created and bound to the datasource control. Therefore, we can use this event to check whether the inventory is 0, if it is 0, set the Beijing color of the row to yellow. The Code is as follows:

Public void productsgridview_rowdatabound (Object sender,
Gridviewroweventargs E)
{
If (E. Row. rowtype = datacontrolrowtype. datarow)
{
Int unitsinstock = convert. toint32 (databinder. eval (E. Row. dataitem, "unitsinstock "));
If (unitsinstock = 0)
E. Row. backcolor = color. Yellow;
}
}

First, this event first checks whether the current row belongs to the datarow type, because rows such as headerrow and footerrow in the gridview do not contain actual data. Therefore, we do not need to use headerrow and footerrow, but to get the contents of unitesinstock, we use databinder. eval method retrieves its content, converts it to int type, and then determines whether it is 0. If it is 0, set the background color of its row to yellow. Shows the program running result:

  2. pagination and sorting of the gridview

In Asp.net 1.1, DataGrid paging is very common. In Asp.net 2.0, there are still two paging methods. One is the default paging method. For example, if there are 1000 data entries, 10 data entries are displayed on each page, therefore, each page request must read 1000 pieces of data from the database, but 10 pieces of data are displayed each time a page is displayed, reducing the speed and performance. The other is the custom paging mode. For example, if 10 pieces of data are displayed on each page, each time the program redirects to the page, only 10 pieces of data are retrieved from the database and displayed to the user, instead of 1000 pieces of data each time. Therefore, the performance is greatly improved.

In Asp.net 2.0, it is very easy to use the sqldatasource Control for paging. The sqldatasource data source control is used to deal with databases. It can read data in the database and be bound with controls such as the gridview. In the following demonstration, drag a sqldatasource control, set its data source to the northwind database in SQL Server, drag a gridview control, and click the Smart tag of the gridview, in the pop-up menu, select "enable paging" and "enable sorting", that is, to allow paging and sorting, you can complete the paging and sorting functions, isn't it easy? As shown in:

In the paging effect, sometimes we want to let users know what pages are currently being viewed. How can we achieve this? In the gridview, there is a pageindex attribute that indicates the page number (starting from 0). You only need to write the following code in the HTML code of the page to achieve the effect:

<I> you are viewing page
<% = Productsgridview. pageindex + 1%>
Of
<% = Productsgridview. pagecount %>
</I>

The complete code is as follows:

<Form ID = "form1" runat = "server">
<Div>
<Asp: sqldatasource id = "productdatasource" runat = "server"
Selectcommand = "select [productname], [unitprice],
[Unitsinstock], [quantityperunit] from [products]"
Connectionstring = "<% $ connectionstrings: nwconnectionstring %>">
</ASP: sqldatasource>
<Asp: gridview id = "productsgridview" runat = "server"
Performanceid = "productdatasource" autogeneratecolumns = "false"
Allowsorting = "true" borderwidth = "2px" backcolor = "white" gridlines = "NONE" cellpadding = "3"
Cellspacing = "1" borderstyle = "ridge" bordercolor = "white" allowpaging = "true">
<Footerstyle forecolor = "black" backcolor = "# c6c3c6"> </footerstyle>
<Pagerstyle forecolor = "black" horizontalalign = "right" backcolor = "# c6c3c6"> </pagerstyle>
<Headerstyle forecolor = "# e7e7ff" font-bold = "true" backcolor = "# 4a3c8c">
<Columns>
<Asp: boundfield headertext = "product" datafield = "productname" sortexpression = "productname">
</ASP: boundfield>
<Asp: boundfield headertext = "unit price" datafield = "unitprice" sortexpression = "unitprice"
Dataformatstring = "{0: c}">
<Itemstyle horizontalalign = "right"> </itemstyle>
</ASP: boundfield>
<Asp: boundfield headertext = "units in stock" datafield = "unitsinstock"
Sortexpression = "unitsinstock" dataformatstring = "{0: d}">
<Itemstyle horizontalalign = "right"> </itemstyle>
</ASP: boundfield>
<Asp: boundfield headertext = "quantity per unit" datafield = "quantityperunit"> </ASP: boundfield>
</Columns>
<Selectedrowstyle forecolor = "white" font-bold = "true" backcolor = "# 9471de"> </selectedrowstyle>
<Rowstyle forecolor = "black" backcolor = "# dedfde"> </rowstyle>
</ASP: gridview>
<I> you are viewing page
<% = Productsgridview. pageindex + 1%>
Of
<% = Productsgridview. pagecount %>
</I>
</Div>
</Form>

Shows the implementation effect:

Note that you can click the name of each field in the gridview, such as product, unit price, and so on for sorting, which is very convenient. If you want to display the number of data entries displayed on each page, you only need to set the pagesize attribute of the gridview.
  3. Use images in the gridview

In Asp.net 1.1, if you want to use images, you need to set the templatecolumn template column. In ASP. Ne 2.0, the imagefield column is provided to display images in the gridview. Next, we will design a simple album list to show you how to use images in the gridview. The results of the data table are as follows, and assume that the user has uploaded a photo, therefore, we will focus on how to display images in the gridview.

· Pictureid-the serial number of the image, which is automatically increased.

· Title-image title

· Dateadded-Image Upload date

· Pictureurl-relative path of the uploaded Image

Next, drag a gridview to the IDE environment and bind it to sqldatasource. Because we want to display the actual image in the gridview, we first select the Smart Tag tag of the gridview and select "Edit columns" in the pop-up menu ", remove the pictureurl binding field, add an imagefield binding field, and set the dataimageurlfield attribute of the imagefield to the pictureurl field to display the image path, as shown in:

The following is the relevant HTML code:

<Asp: gridview id = "gridview1" runat = "server"
Datasource = '<% # getdata () %>' autogeneratecolumns = "false"
Borderwidth = "1px" backcolor = "white" cellpadding = "3" borderstyle = "NONE"
Bordercolor = "# cccccc" font-names = "Arial">
<Footerstyle forecolor = "#000066" backcolor = "white"> </footerstyle>
<Pagerstyle forecolor = "#000066" horizontalalign = "left"
Backcolor = "white"> </pagerstyle>
<Headerstyle forecolor = "white" font-bold = "true"
Backcolor = "#006699">
<Columns>
<Asp: boundfield headertext = "picutre ID" datafield = "pictureid">
<Itemstyle horizontalalign = "center"
Verticalalign = "Middle"> </itemstyle>
</ASP: boundfield>
<Asp: boundfield headertext = "title" datafield = "title"> </ASP: boundfield>
<Asp: boundfield headertext = "date added" datafield = "dateadded"
Dataformatstring = "{0: d}">
<Itemstyle horizontalalign = "center"> </itemstyle>
</ASP: boundfield>
<Asp: imagefield dataimageurlfield = "pictureurl"> </ASP: imagefield>
</Columns>
<Selectedrowstyle forecolor = "white" font-bold = "true"
Backcolor = "#669999"> </selectedrowstyle>
<Rowstyle forecolor = "#000066"> </rowstyle>
</ASP: gridview>

We also create a data table by writing code manually, as shown in the following code:

Datatable getdata ()
{
// This method creates a datatable with four rows. Each row has
// Following schema:
// Pictureid int
// Pictureurl string
// Title string
// Dateadded datetime
Datatable dt = new datatable ();
// Define the table's schema
DT. Columns. Add (New datacolumn ("pictureid", typeof (INT )));
DT. Columns. Add (New datacolumn ("pictureurl", typeof (string )));
DT. Columns. Add (New datacolumn ("title", typeof (string )));
DT. Columns. Add (New datacolumn ("dateadded", typeof (datetime )));
// Create the four records
Datarow DR = DT. newrow ();
Dr ["pictureid"] = 1;
Dr ["pictureurl"] = resolveurl ("~ /Displayingimages/images/blue hills.jpg ");
Dr ["title"] = "Blue Hills ";
Dr ["dateadded"] = new datetime (2005, 1, 15 );
DT. Rows. Add (DR );
Dr = DT. newrow ();
Dr ["pictureid"] = 2;
Dr ["pictureurl"] = resolveurl ("~ /Displayingimages/images/sunset.jpg ");
Dr ["title"] = "sunset ";
Dr ["dateadded"] = new datetime (2005, 1, 21 );
DT. Rows. Add (DR );
Dr = DT. newrow ();
Dr ["pictureid"] = 3;
Dr ["pictureurl"] =
Resolveurl ("~ /Displayingimages/images/water lilies.jpg ");
Dr ["title"] = "water lilies ";
Dr ["dateadded"] = new datetime (2005, 2, 1 );
DT. Rows. Add (DR );
Dr = DT. newrow ();
Dr ["pictureid"] = 4;
Dr ["pictureurl"] = resolveurl ("~ /Displayingimages/images/winter.jpg ");
Dr ["title"] = "Winter ";
Dr ["dateadded"] = new datetime (2005, 2, 18 );
DT. Rows. Add (DR );
Return DT;
}

The result is shown in

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.