6

I have a gridview that loads data from database. The data is displayed in the gridview for the first time sorted by datetime. On one column of that gridview I want to allow sorting, for example on the main_post column. I had tried this, but the gridview still did not sort when I click the header of the column.

This is my front-end code for gridview:

<asp:DataGrid ID="Datagrid1" runat="server" 
    AllowPaging="True" 
    AllowSorting="True" 
    OnSorting="ComponentGridView_Sorting">
    <Columns>
        <asp:BoundColumn DataField="main_post" HeaderText="Header Post ID" 
            SortExpression="ComponentGridView_Sorting" />
    </Columns>
</asp:DataGrid>

My back-end code:

protected void loadData()
{
    DataTable dtTemp;
    dtTemp = objDBInterface.getResults(strSQL);
    Datagrid1.DataSource = dtTemp;
    Datagrid1.DataBind();
    ViewState["dtbl"] = dtTemp;
}

protected void ComponentGridView_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dataTable = ViewState["dtbl"] as DataTable;
        if (dataTable != null)
        {
            DataView dataView = new DataView(dataTable);
            dataView.Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection);
            Datagrid1.DataSource = dataView;
            Datagrid1.DataBind();
        }
    }
    private string ConvertSortDirection(SortDirection sortDirection)
    {
        string newSortDirection = String.Empty;
        switch (sortDirection)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;
            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }

        return newSortDirection;
    }

I dont have any error and I dont know where my mistake is, could somebody please help me to solve this problem?

Thanks in advance.

4 Answers 4

5

Simple, set Allowsorting property true and add sorting event in your gridview.

<asp:GridView ID="GridView1" runat="server" AllowSorting="true" 
      OnSorting="GridView1_Sorting">
</asp:GridView>   

Now add Event OnSorting in .cs file

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{ 
    SetSortDirection(SortDireaction);
    if (dataTable != null)
    {
       dataTable.DefaultView.Sort = e.SortExpression + " " +_sortDirection;
        GridView1.DataSource = dataTable;
        GridView1.DataBind();
        SortDireaction = _sortDirection;
    }
} 
protected void SetSortDirection(string sortDirection)
{
    if (sortDirection == "ASC")
    {
        _sortDirection = "DESC";
    }
    else
    {
        _sortDirection = "ASC";
    }
} 

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

Comments

2

I got the solution. Hope this will help others people that face this similar problem. On .aspx page need to change:

from OnSorting="ComponentGridView_Sorting"

to onsortcommand="ComponentGridView_Sorting"

Then put this code on aspx.cs(back-end code):

protected void Datagrid1_SortCommand(object source, DataGridSortCommandEventArgs e)
    {
        string strSQL;
        DataTable dt;
        strSQL = "YOUR SELECT STATEMENT (SQL)";
        dt = strSQL;
            {
                string SortDir = string.Empty;
                if (dir == SortDirection.Ascending)
                {
                    dir = SortDirection.Descending;
                    SortDir = "Desc";
                }
                else
                {
                    dir = SortDirection.Ascending;
                    SortDir = "Asc";
                }
                DataView sortedView = new DataView(dt);
                sortedView.Sort = e.SortExpression + " " + SortDir;
                Datagrid1.DataSource = sortedView;
                Datagrid1.DataBind();
            }
    }

    protected SortDirection dir
    {
        get
        {
            if (ViewState["dirState"] == null)
            {
                ViewState["dirState"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["dirState"];
        }
        set
        {
            ViewState["dirState"] = value;
        }
    }

Comments

1

Do not take tension developers it's really too easy follow my steps

Step 1 Create GridView

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"  class="w3-table-all"
        OnPageIndexChanging="OnPageIndexChanging" PageSize="20" >
        <Columns>
            <asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="250px" DataField="sn_no" HeaderText="ID" />
            <asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="name" HeaderText="Name" />
            <asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="mo" HeaderText="Mobile" />
            <asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="email" HeaderText="Email Id" />
            <asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="loc" HeaderText="Location" />
            <asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="date" HeaderText="Date" />
            <asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="day2" HeaderText="Day" />
            <asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="date" HeaderText="Date" />
            <asp:BoundField HeaderStyle-CssClass="w3-blue" ItemStyle-CssClass="w3-hover-green" ItemStyle-Width="500px" DataField="time" HeaderText="Time" />
        </Columns>

  </asp:GridView>

Step 2 Goto *.aspx.cs file and write

a). For descending order

cmd = new MySqlCommand("SELECT * FROM appointment ORDER BY sn_no DESC", con);

b). For ascending order

cmd = new MySqlCommand("SELECT * FROM appointment ORDER BY sn_no ASC", con);

Thanks with love #Vaibhav Yadav Vaibhav Designs http://vaibhavdesigns.org for more ...

1 Comment

**Comment Guys **
0
    <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="empid" DataSourceID="SqlDataSource1" EnableModelValidation="True" ForeColor="#333333" GridLines="None">

1 Comment

You may provide some explanation about your answer.

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.