Tuesday, May 3, 2016

Asp.net Gridview sorting example in ascending and descending order code behind

In this article I am going to explain how to do sorting in gridview data control by column header in ascending and descending order code behind.

Asp.net Gridview sorting example in ascending and descending order code behind

Description:
We have three ways to implement this functionality: Jquery, Sql datasource and code behind. Here in this tutorial I am going to implement using code behind.



Implementation:

Add a webfrom to project and add the Gridview data control from toolbox to webform.

Create Store procedure to get data
Create proc SpGetMovie
AS
BEGIN
Select * from dbo.Tb_Movie
End

HTML Markup:
<asp:gridview ID="grdmovie" runat="server" AutoGenerateColumns="False"
            AllowSorting="True" AllowPaging="True"
            CellPadding="4" ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
    <asp:BoundField DataField="Name" HeaderText="Movie Name" SortExpression="name"/>
     <asp:BoundField DataField="Genre" HeaderText="Genre" SortExpression="Genre" />
      <asp:BoundField DataField="Budget" HeaderText="Budget" SortExpression="Budget" />
    </Columns>
        <EditRowStyle BackColor="#999999" />
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#E9E7E2" />
        <SortedAscendingHeaderStyle BackColor="#506C8C" />
        <SortedDescendingCellStyle BackColor="#FFFDF8" />
        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:gridview>

Import the namespace
C# Code:
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

VB.net Code:
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data

Create a method to get data and caal it on page load event.
C# Code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)

        {
            grdmovie.DataSource = BindGridview();
            grdmovie.DataBind();
        }
    }
    public DataTable BindGridview()
    {
        SqlDataAdapter adp = new SqlDataAdapter("SpGetMovie", con);
        adp.SelectCommand.CommandType = CommandType.StoredProcedure;
        dt = new DataTable();
        adp.Fill(dt);
        return dt;
    }

VB.net Code:
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
    Dim dt As New DataTable()
  Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            grdmovie.DataSource = BindGridview()
            grdmovie.DataBind()
        End If
    End Sub
    Public Function BindGridview() As DataTable
        Dim adp As New SqlDataAdapter("SpGetMovie", con)
        adp.SelectCommand.CommandType = CommandType.StoredProcedure
        dt = New DataTable()
        adp.Fill(dt)
        Return dt
    End Function

Create property to store direction in viewstate
C# Code:
public SortDirection dir
    {
        get
        {
            if (ViewState["directionState"] == null)
            {
                ViewState["directionState"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["directionState"];
        }
        set
        { ViewState["directionState"] = value; }
    }

VB.net Code:
Public Property dir() As SortDirection
        Get
            If ViewState("directionState") Is Nothing Then
                ViewState("directionState") = SortDirection.Ascending
            End If
            Return DirectCast(ViewState("directionState"), SortDirection)
        End Get
        Set(value As SortDirection)
            ViewState("directionState") = value
        End Set
    End Property

Sorting event of Gridview
Write the below given code on sorting event of gridview.

C# Code:
protected void grdmovie_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortExpression = e.SortExpression;
        sortExpression = string.Empty;
        if (dir == SortDirection.Ascending)
        {
            dir = SortDirection.Descending;
            sortExpression = "Desc";
        }
        else
        {
            dir = SortDirection.Ascending;
            sortExpression = "Asc";
        }
        DataView sortedView = new DataView(BindGridview());
        sortedView.Sort = e.SortExpression + " " + sortExpression;
        grdmovie.DataSource = sortedView;
        grdmovie.DataBind();
    }

VB.net Code:
Protected Sub grdmovie_Sorting(sender As Object, e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdmovie.Sorting
        Dim sortExpression As String = e.SortExpression
        sortExpression = String.Empty
        If dir = SortDirection.Ascending Then
            dir = SortDirection.Descending
            sortExpression = "Desc"
        Else
            dir = SortDirection.Ascending
            sortExpression = "Asc"
        End If
        Dim sortedView As New DataView(BindGridview())
        sortedView.Sort = Convert.ToString(e.SortExpression + " ") & sortExpression
        grdmovie.DataSource = sortedView
        grdmovie.DataBind()
    End Sub



No comments:

Post a Comment