Tuesday, March 13, 2012

GridView Sorting Vb.Net

GridView sorting is very easy to enable. But only few functionalities are available out of the box, so still a few things should be configured and coded. The first thing to enable sorting is AllowSorting = true. Then SortExpression has to be specified. Normally column name has to be given for the SortExpression. With this the GridView  view will be able to sort based on the SortExpression given.

After configuring the above when you click on the sort link in the header of the respective column, an exception will be thrown that the Sorting event is not handled. In this event we need to sort the data using a DataView. DataView has a Sort which we can use to pass the expression.

Actually when a GridView is sorted in either ascending or descending order the next expected has to be opposite for the first sorting. If the first sorting is ascending then the second sorting has to be descending.

DataView can be obtained from Data Table’s DefaultView. Data View’s Sort property can sort the data based on the given ascending or descending suffix. After this rebind the GridView  to sort.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>



Untitled Page



ID="GridView1" ShowFooter="true" >








Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Private Property SortDirection() As String
Get
If (ViewState("SortDirection") Is Nothing) Then ViewState("SortDirection") = String.Empty
Return ViewState("SortDirection").ToString()
End Get
Set(ByVal value As String)
ViewState("SortDirection") = value
End Set
End Property
Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
If (Not IsPostBack) Then
GridView1.DataSource = GetSortableData(String.Empty) 'System.Drawing.FontFamily.Families

View the original article here

No comments:

Post a Comment