Ifwat
Ifwat

Reputation: 1553

Sorting gridview column in asp.net

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.

Upvotes: 6

Views: 69503

Answers (4)

iRIS
iRIS

Reputation: 19

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 ...

Upvotes: 1

Shekhar Patel
Shekhar Patel

Reputation: 671

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";
    }
} 

Upvotes: 5

RAJESH RAJESH
RAJESH RAJESH

Reputation: 1

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

Upvotes: 0

Ifwat
Ifwat

Reputation: 1553

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;
        }
    }

Upvotes: 2

Related Questions