Myworld Myworld - 3 months ago 29
ASP.NET (C#) Question

sorting gridview

I have a gridview where I bind a datasource, I had to add sorting for this gridview; I added the code below to that but It didn't work well.

private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
string m_SortDirection = String.Empty;

switch (sortDireciton)
{
case SortDirection.Ascending:
m_SortDirection = "ASC";
break;

case SortDirection.Descending:
m_SortDirection = "DESC";
break;
}

return m_SortDirection;
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable m_DataTable = GridView1.DataSource as DataTable;

if (m_DataTable != null)
{
DataView m_DataView = new DataView(m_DataTable);
m_DataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

GridView1.DataSource = m_DataView;
GridView1.DataBind();
}
}

Answer

you can use this, as I had the same problem and I solve it like this.

public string SortingExpression
{
    get
    {
        if (this.ViewState["SortExpression"] == null)
            return "";
        else
            return (string)this.ViewState["SortExpression"];
    }

    set
    {
        this.ViewState["SortExpression"] = value;
    }
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    DataTable m_DataTable = GridView1.DataSource as DataTable;

    if (m_DataTable != null)
    {
        DataView m_DataView = new DataView(m_DataTable);
        SortingExpression = e.SortExpression + " " + (SortingExpression.Contains("ASC") ? "DESC" : "ASC");
        m_DataView.Sort =SortingExpression;

        GridView1.DataSource = m_DataView;
        GridView1.DataBind();
    }
}