1

I am using asp.net web-form and gridview on several pages to display data. I bind gridview from codebehind file.

SO far i am able to use following code to bind datasource to gridview and also enable paging but i a facing problem to enable sorting on the same grid. Any point or help regarding how to enable paging to make it work with the below code.

I also have addition fields which are not part of this code which i use for additional functionality onrowdatabound="GridView1_RowDataBound" onrowcommand="GridView1_RowCommand"

.ASPX File

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ID" 
           Width="990px" BackColor="White" BorderColor="WhiteSmoke" BorderStyle="None" BorderWidth="0px" CellPadding="5" 
            Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black" GridLines="Horizontal" PageSize="10" CssClass="myheader"  AllowSorting="true" 
             onrowdatabound="GridView1_RowDataBound"  onrowcommand="GridView1_RowCommand" onpageindexchanging="GridView1_PageIndexChanging" >
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
                <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
                <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date"  DataFormatString="{0:yyyy/MM/dd}"/>
            </Columns>
            <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
            <HeaderStyle  Height="32px" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" BorderStyle="None" />
            <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#242121" />
            <RowStyle   BorderColor="#f5f5f5" BorderStyle="Notset"/>
   </asp:GridView>

CODE BEHIND

protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
        GetDetails();
    }
}   


   protected void GetDetails()
{
    string strSql = "SELECT * FROM Test_Table Order by Date Desc ";
    DataSet ds = DataProvider.Connect_Select(strSql);
    GridView1.DataSource = ds;
    GridView1.DataBind();

}

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    GetDetails();
}

UPDATE: Code updated to

.ASPX

OnSorting="GridView1_OnSorting"

CODE BEHIND

    protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
{
    string strSql = "SELECT * FROM Test_Table ";
    DataSet ds = DataProvider.Connect_Select(strSql);
    DataTable dataTable = ds.Tables[0];
    DataTable dataTable = ds.Tables[0];

    if (dataTable != null)
    {
        DataView dataView = new DataView(dataTable);
        dataView.Sort = e.SortExpression + " "+e.SortDirection;
        GridView1.DataSource = dataView;
        GridView1.DataBind();
    }
}
1
  • <PagerSettings PageButtonCount="8"></PagerSettings> Commented Feb 4, 2014 at 5:20

3 Answers 3

1

You should create sorting event like this :

    protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
    {

        //TODO write tour code here to get data from database;
         DataTable dataTable = your datatable get from your db;

        if (dataTable != null)
        {
                if (e.SortDirection.ToString() == "Ascending")
                {
                    dataView.Sort = e.SortExpression + " ASC";
                }
                else if (e.SortDirection.ToString() == "Descending")
                {
                    dataView.Sort = e.SortExpression + " DESC";
                }

            DataView dataView = new DataView(dataTable);
            dataView.Sort = e.SortExpression + " "+e.SortDirection;
            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }
    }


**e.SortExpression** provides sorting column name 

**e.SortDirection** provides sorting direction like ASC or DESC.

Also you can take sort direction in view state on page

private string GridViewSortDirection
    {
        get { return ViewState["SortDirection"] as string ?? "DESC"; }
        set { ViewState["SortDirection"] = value; }
    }

private void SetSortDirection()
        {
            GridViewSortDirection = (GridViewSortDirection.ToUpper() == "DESC") ? "ASC" : "DESC";
        }

I hope above code help you.

Sign up to request clarification or add additional context in comments.

4 Comments

I made following changes OnSorting="GridView1_OnSorting" and then your code still it is not working..
I updated my question with your code snippet but it is not working did i do something wrong
Ditnt work for some reason so i am posting code which is almost similar to your but slightly different..
The OnSorting() logic doesn't make sense. You've defined dataView after its first use. And you've set dataView.Sort once in your if statement (where you also have cast SortDirection to string instead of comparing it to SortDirection.Ascending or SortDirection.Descending) and then you set dataView.Sort again just below that conditional statement.
1

SOLUTION

I have deleted the old code it had a bug as sorting was not working properly when one us to move back and forth from one page to another. Below code is test and is working well with sorting & paging.

public partial class _Default : System.Web.UI.Page
{

    string Sort_Direction = "Date DESC";

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
           // GetRegistrationDetails();
            ViewState["SortExpr"] = Sort_Direction;
            DataView dv = Getdata();
            GridView1.DataSource = dv;
            GridView1.DataBind();
        }
    }

    private DataView Getdata()
    {      
        string strSql = "SELECT * ROM TEST_Table ";
        DataSet ds = DataProvider.Connect_Select(strSql);
        DataView dv = ds.Tables[0].DefaultView;
        dv.Sort = ViewState["SortExpr"].ToString();
        return dv;
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        DataView dv = Getdata();
        GridView1.DataSource = dv;
        GridView1.DataBind();
    }

    protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
    {
        GridView1.PageIndex = 0;
        string[] SortOrder = ViewState["SortExpr"].ToString().Split(' ');
        if (SortOrder[0] == e.SortExpression)
        {
            if (SortOrder[1] == "ASC")
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "DESC";
            }
            else
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
            }
        }
        else
        {
            ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
        }
        GridView1.DataSource = Getdata();
        GridView1.DataBind();
    }
}

5 Comments

@KnowledgeSeeker this code won't persist the sort expression and sort direction on PageIndexChanging event. See my answer.
@ekad, yes you are right. with this code i am able to sort other field but if i am on page 3 & i sort it still remains on that page while it should go to first page... but for some reason you code was not work (Before you updated you code 3rd time).. how can i resolve that issue in my code..
with this code i am able to sort but if i am on page 3 & i do a new sort it still remains on that page while it should go to first page... still buggy..
What do you mean by new sort? Are you using this code of yours or my code? If it's my code, please comment below my answer instead.
@ekad, i am using my code version and i have further modified it to make it work properly... I will update my answer in 10 minutes.. as i am testing it..
0

You have already set AllowSorting="true" and the SortExpression property for each column, so the next step is keeping the last sort expression and sort direction between postbacks, and using them in PageIndexChanging and Sorting event.

I would suggest using ViewState to keep the last sort expression and sort direction

private string SortExpression
{
    get
    {
        return ViewState["SortExpression"] == null ? string.Empty : ViewState["SortExpression"].ToString();
    }
    set
    {
        ViewState["SortExpression"] = value;
    }
}

private string SortDirection
{
    get
    {
        return ViewState["SortDirection"] == null ? string.Empty : ViewState["SortDirection"].ToString();
    }
    set
    {
        ViewState["SortDirection"] = value;
    }
}

This is the method to get the next sort direction:

private string GetSortDirection(string sortExpression)
{
    if (sortExpression == this.SortExpression)
    {
        // reverse the sort direction when current sort expression is the same as the last time
        if (this.SortDirection == "ASC")
        {
            return "DESC";
        }
        else
        {
            return "ASC";
        }
    }
    else
    {
        // always return ASC when current sort expression is different than the last time
        return "ASC";
    }
}

GetDetails method will need to know the sort expression and sort direction, so add sortExpression and sortDirection parameter:

protected void GetDetails(string sortExpression, string sortDirection)
{
    string strSql = string.Format("SELECT * FROM Test_Table Order by {0} {1}", sortExpression, sortDirection);

    DataSet ds = DataProvider.Connect_Select(strSql);
    GridView1.DataSource = ds;
    GridView1.DataBind();

    // save current sort expression and sort direction to ViewState
    this.SortExpression = sortExpression;
    this.SortDirection = sortDirection;
}

Make sure you add OnSorting="GridView1_Sorting" to GridView1 markup code:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ID" 
    Width="990px" BackColor="White" BorderColor="WhiteSmoke" BorderStyle="None" BorderWidth="0px" CellPadding="5" 
    Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black" GridLines="Horizontal" PageSize="10" CssClass="myheader"  AllowSorting="true" 
    OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand" onpageindexchanging="GridView1_PageIndexChanging"
    OnSorting="GridView1_Sorting" >

Assuming that the default sort expression is Date and the default sort direction is DESC, this is what Page_Load, GridView1_PageIndexChanging, and GridView1_Sorting methods will look like

private const string DEFAULT_SORT_EXPRESSION = "Date";
private const string DEFAULT_SORT_DIRECTION = "DESC";

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GetDetails(DEFAULT_SORT_EXPRESSION, DEFAULT_SORT_DIRECTION);
    }
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;

    // use the last sort expression and sort direction
    GetDetails(this.SortExpression, this.SortDirection);
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    // get next sort direction
    string sortDirection = GetSortDirection(e.SortExpression);

    // get data with current sort expression and sort direction
    GetDetails(e.SortExpression, sortDirection);
}

UPDATE

If you want to go to page 1 when sorting, just add GridView1.PageIndex = 0; to GridView1_Sorting:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    GridView1.PageIndex = 0;

    // get next sort direction
    string sortDirection = GetSortDirection(e.SortExpression);

    // get data with current sort expression and sort direction
    GetDetails(e.SortExpression, sortDirection);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.