Let the datagrid of ASP.net be sorted, selectable, pagination _ self-study process

Source: Internet
Author: User
Tags error handling html page
The DataGrid is an important control in asp.net, and often we make the DataGrid paginated and sortable, sometimes with the option to be added. These are the methods that are often needed, but they are relatively simple.

Design ideas:
For convenience, we connect the Orders table of the Northwind database for SQL Server 2000 and get a data view of the table from the database. Use the SortCommand event in the DataGrid to implement sorting. Implement the selection with a template column plus a CheckBox control. You can use the paging option in the DataGrid's Property builder or modify the HTML implementation pagination yourself.

Html:

Add a DataGrid, named Dgorder.
A template column is added, and a CheckBox control named CB is placed in the template column. This column is used to implement the selection
Adds a sort expression sortexpression to each column that you want to sort.
Use the dataformatstring of the column to format the column, like dataformatstring= "{0:d}" to display the date format.
Set pagesize= "15" to display 15 rows of data per page, allowpaging= "True" to allow paging.

Entire HTML page code:

<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=" borderstyle= "Solid" backcolor= "white" Gridlines= "Vertical" forecolor= "Black" allowpaging= "true" showfooter= "true" >

<selecteditemstyle forecolor= "white" backcolor= "Black" ></SelectedItemStyle>

<alternatingitemstyle backcolor= "#EEEEEE" ></AlternatingItemStyle>


<footerstyle forecolor= "White" backcolor= "#6876C5" ></FooterStyle>

<Columns>

<asp:TemplateColumn>

<ItemTemplate>

<font face= "Song Body" >

<asp:checkbox id= "Cb" runat= "Server" ></asp:CheckBox></FONT>

</ItemTemplate>

</asp:TemplateColumn>

<asp:boundcolumn datafield= "OrderID" sortexpression= "OrderID" headertext= "ID" >


</asp:BoundColumn>

<asp:boundcolumn datafield= "ShipCountry" sortexpression= "ShipCountry" headertext= "ShipCountry" >


</asp:BoundColumn>

<asp:boundcolumn datafield= "ShippedDate" sortexpression= "ShippedDate" headertext= "ShippedDate" DataFormatString = ' {0:d} ' >


</asp:BoundColumn>

<asp:boundcolumn datafield= "Freight" sortexpression= "Freight" headertext= "Freight" >


</asp:BoundColumn>

<asp:boundcolumn datafield= "shipaddress" sortexpression= "shipaddress" headertext= "ShipAddress" >


</asp:BoundColumn>

</Columns>

<pagerstyle horizontalalign= "Center" forecolor= "Black" position= "Topandbottom" backcolor= "White" mode= " NumericPages "></PagerStyle>

</asp:datagrid>

</form>







The background class adds the following code:



Imports System.Data.SqlClient



' Get the Data View, the parameter is the column to sort

Private Function GETDV (ByVal strsort as String) as DataView

' Define a database connection

Dim DV as DataView

Dim CN as New SqlConnection ()

Try

' Initialize connection string

CN. ConnectionString = "Data source=pmserver;initial catalog=northwind;persist security Info=false;user Id=sa; Password=sa; "

CN. Open ()

' Get data from the Orders table 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 ") ' The Public error handling page of the Jump program

#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

' Get sorted columns

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

Dgorder.datasource = GETDV (ViewState ("StrSort"). ToString ())

Dgorder.databind ()

End Sub



' Paging

Private Sub dgorder_pageindexchanged (ByVal source as Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles dgorder.pageindexchanged

' Get page number of pagination

Dgorder.currentpageindex = E.newpageindex

Dgorder.datasource = GETDV (ViewState ("StrSort"). ToString ())

Dgorder.databind ()

End Sub

The results of the operation are as follows: (Click on the column headers to sort)



In order to know which records the user chooses, we can use DataGridItem's FindControl to get the checkbox value, we add a button, and then write the following code:

Private Sub button1_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" (""

' Loop the entry of the 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 + = "was selected!" ') </script> "

RegisterClientScriptBlock ("System Messages", Strscript)

End Sub

The code above RegisterClientScriptBlock adds a Java Script Popup dialog box. (In fact, VB Script dialog box than Java Script dialog more display and control mode, but Netscape browser does not support, you can according to the corresponding project in the program to choose what kind of script).

Summarize:

DataGrid is our common Web control, sometimes we can mix with DataList, by modifying the HTML page, can achieve good page effect. It's just an example of how I wrote the Data Access section (SQL) to the page to make it easier to understand the whole process. In software development, we generally have access to the data part of the data layer, page call data layer to get the data, so logic clear, modify and maintenance are very convenient.

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.