Enable the DataGrid of ASP. NET to be sorted, selectable, and paging

Source: Internet
Author: User

DataGrid is an important control in ASP. NET. It is often made into a paginated and sortable DataGrid, and sometimes the selection function needs to be added. These are frequently used methods, which are actually relatively simple.

Design Concept:
For convenience, we connect to the orders table of the northwind database of SQL Server 2000 to obtain the data view of this table from the database. Use the DataGrid sortcommand event to sort data. Add the checkbox control to a template column for selection. You can use the "pagination" option of the property generator of the DataGrid or modify HTML to implement pagination.

HTML:

Add a DataGrid named dgorder.
A template column is added with a checkbox control named CB in the template column. This column is used for selection.
Add a sort expression sortexpression to each column to be sorted.
Use the dataformatstring of the column to format the column, such as dataformatstring = "{0: d}" display date format.
Set pagesize = "15" to display 15 rows of data per page, and allowpaging = "true" to allow paging.

Entire HTML pageCode:

<Form ID = "form1" method = "Post" runat = "server">

<Asp: dataGrid id = "dgorder" runat = "server" Height = "515px" width = "718px" autogeneratecolumns = "false" allowsorting = "true" cellpadding = "4" borderwidth = "1px "bordercolor =" # a0abeb "pagesize =" 15 "borderstyle =" solid "backcolor =" white "gridlines =" vertical "forecolor =" black "allowpaging =" true "showfooter =" true ">

<Selecteditemstyle forecolor = "white" backcolor = "black"> </selecteditemstyle>

<Alternatingitemstyle backcolor = "# eeeeee"> </alternatingitemstyle>

<Headerstyle horizontalalign = "center" forecolor = "white" bordercolor = "#6876c5" backcolor = "#6876c5">

<Footerstyle forecolor = "white" backcolor = "#6876c5"> </footerstyle>

<Columns>

<Asp: templatecolumn>

<Itemtemplate>

<Font face = "">

<Asp: checkbox id = "CB" runat = "server"> </ASP: checkbox> </font>

</Itemtemplate>

</ASP: templatecolumn>

<Asp: boundcolumn datafield = "orderid" sortexpression = "orderid" headertext = "ID">

<Headerstyle width = "180px">

</ASP: boundcolumn>

<Asp: boundcolumn datafield = "shipcountry" sortexpression = "shipcountry" headertext = "shipcountry">

<Headerstyle width = "180px">

</ASP: boundcolumn>

<Asp: boundcolumn datafield = "shippeddate" sortexpression = "shippeddate" headertext = "shippeddate" dataformatstring = "{0: d}">

<Headerstyle width = "180px">

</ASP: boundcolumn>

<Asp: boundcolumn datafield = "freight" sortexpression = "freight" headertext = "freight">

<Headerstyle width = "180px">

</ASP: boundcolumn>

<Asp: boundcolumn datafield = "shipaddress" sortexpression = "shipaddress" headertext = "shipaddress">

<Headerstyle width = "480px">

</ASP: boundcolumn>

</Columns>

<Pagerstyle horizontalalign = "center" forecolor = "black" position = "topandbottom" backcolor = "white" mode = "numericpages"> </pagerstyle>

</ASP: DataGrid>

</Form>

Add the following code to the background class:

Imports system. Data. sqlclient

'Get the data view. The parameter is the column to be sorted.

Private function getdv (byval strsort as string) as dataview

'Define database connection

Dim DV as dataview

Dim cn as new sqlconnection ()

Try

'Initialize the connection string

CN. connectionstring = "Data Source = pmserver; initial catalog = northwind; persist Security info = false; user id = sa; Password = sa ;"

CN. open ()

'Obtain the orders table data from northwind.

Dim ADP as sqldataadapter = new sqldataadapter ("select * from orders", CN)

Dim ds as new dataset ()

ADP. Fill (DS)

'Get the data view

DV = Ds. Tables (0). defaultview

Catch ex as exception

# If debug then

Session ("error") = ex. tostring ()

Response. Redirect (".../error. aspx") 'jumpProgramPublic error handling page

# End if

Finally

'Close the connection

CN. Close ()

End try

'Sort

DV. Sort = strsort

Return dv

End Function

Private sub page_load (byval sender as system. Object, byval e as system. eventargs) handles mybase. Load

If not ispostback then

Viewstate ("strsort") = "orderid"

Dgorder. datasource = getdv (viewstate ("strsort"). tostring ())

Dgorder. databind ()

End if

End sub

'Sort

Private sub dgorder_sortcommand (byval source as object, byval e as system. Web. UI. webcontrols. datagridsortcommandeventargs) handles dgorder. sortcommand

Dgorder. currentpageindex = 0

'Column to be sorted

Viewstate ("strsort") = E. sortexpression. tostring ()

Dgorder. datasource = getdv (viewstate ("strsort"). tostring ())

Dgorder. databind ()

End sub

'Pagination

Private sub dgorder_pageindexchanged (byval source as object, byval e as system. Web. UI. webcontrols. datagridpagechangedeventargs) handles dgorder. pageindexchanged

'Get the page number of the page

Dgorder. currentpageindex = E. newpageindex

Dgorder. datasource = getdv (viewstate ("strsort"). tostring ())

Dgorder. databind ()

End sub

Shows the running result: (click the column header to sort)

To know which records are selected, we can use the findcontrol of the datagriditem to get the checkbox value. Let's add a button and then write the following code:

Private sub button#click (byval sender as system. Object, byval e as system. eventargs) handles button1.click

Dim item as datagriditem

Dim strscript as string

Strscript = "<script language = JavaScript> alert ('"

'Items in the cyclic table, findcontrol

For each item in me. dgorder. Items

If ctype (item. findcontrol ("CB"), system. Web. UI. webcontrols. checkbox). Checked then

Try

Strscript + = item. cells (1). Text & Space (2)

Catch ex as exception

End try

End if

Next

Strscript + = "selected! ') </SCRIPT>"

Registerclientscriptblock ("system message", strscript)

End sub

The preceding Code registerclientscriptblock adds a Java Script dialog box. (In fact, the VB Script dialog box has more display and control modes than the Java Script dialog box, but the Netscape browser does not support it, you can select which script to use in the program based on the corresponding project ).

Summary:

DataGrid is a commonly used Web Control. Sometimes it can be used together with datalist. By modifying HTML pages, you can achieve good page effects. The above is just an example. To facilitate the whole process, I wrote the data access part (SQL) to the page. In software development, we generally write the part of the accessed data as the data layer, and call the data layer on the page to obtain the data, so that the logic is clear and easy to modify and maintain.

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.