Thursday, June 13, 2013

Gridview Column Sorting in Asp.net


  Sometimes we need to sort the values display in Gridview columns. Normally data display in Gridview either in ascending or descending depending on the Sql query as per the requirement. Asp.net Gridview has a feature to sort the value when necessary





Source Code :-


<asp:GridView ID="GvRecords" runat="server" Width="100%"
        AutoGenerateColumns="False" onsorting="GvRecords_Sorting"
        AllowSorting="True">
        <Columns>
            <asp:TemplateField HeaderText="ID" SortExpression="ledgerId" >
              <HeaderStyle Font-Underline="true" />
                <ItemTemplate>
                    <asp:Label ID="LblId" runat="server" Text='<%# Eval("ledgerid") %>' CommandArgument='<%# Eval("ledgerid") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name" SortExpression="Ledgername">
             <HeaderStyle Font-Underline="true" />
                <ItemTemplate>
                    <asp:Label ID="Lblname" runat="server" Text='<%# Eval("ledgername") %>' CommandArgument='<%# Eval("ledgername") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>


C# Code :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class GridViewShorting : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataReader dr;
    SqlDataAdapter da;
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
// define the connection string in web config file.
        SelectData();   
    }
    private void SelectData()
    {
        try
        {     
            da = new SqlDataAdapter("select ledgerid,ledgername  from ledgers order by ledgername ", con);          
            ds = new DataSet();
            da.Fill(ds);
            GvRecords.DataSource = ds.Tables[0];
            GvRecords.DataBind();
        }
        catch (Exception ex)
        {
          
        }
      
    }
    protected void GvRecords_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            string sortingDirection = string.Empty;
            if (dir == SortDirection.Ascending)
            {
                dir = SortDirection.Descending;
                sortingDirection = "Desc";
            }
            else
            {
                dir = SortDirection.Ascending;
                sortingDirection = "Asc";
            }
            DataView sortedView = new DataView(GetAllRecordDataTable());
            sortedView.Sort = e.SortExpression + " " + sortingDirection;
            GvRecords.DataSource = sortedView;
            GvRecords.DataBind();
           // SelectData();
        }
        catch (Exception) { }
    }

    public SortDirection dir
    {
        get
        {
            if (ViewState["dirState"] == null)
            {
                ViewState["dirState"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["dirState"];
        }
        set
        {
            ViewState["dirState"] = value;
        }
    }
    public DataTable GetAllRecordDataTable()
    {
        da = new SqlDataAdapter("select ledgerid,ledgername  from ledgers order by ledgername  ", con);
        ds = new DataSet();
        da.Fill(ds);      
        DataTable dtGrid = ds.Tables[0];
        return dtGrid;
    }
}

Declare Connection in Web.Config file :-

<connectionStrings>
    <add name="DBConnection" connectionString="server=myDBS;database=accounts;uid=sa;pwd=raj" providerName="System.Data.SqlClient"/>
   
  </connectionStrings>


No comments:

Post a Comment