排序gridview

时间:2010-10-19 09:11:31

标签: c# asp.net .net sorting gridview

我有一个gridview,我绑定了一个数据源,我不得不为这个gridview添加排序;我在下面添加了代码,但是效果不好。

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

3 个答案:

答案 0 :(得分:1)

如果你的sortdirection总是在升序,那么this可能会有所帮助。

答案 1 :(得分:1)

你可以使用它,因为我有同样的问题,我就这样解决了。

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

答案 2 :(得分:1)

试一试。这种方法对我有用。

dt是包含值的数据表。

 protected void onSorting_Gridview1(object sender, GridViewSortEventArgs e)
            {
                string _sortDirection = dir.ToString();
                if(_sortDirection.Equals("Ascending"))
                {
                _sortDirection = "ASC";
                dir = SortDirection.Descending;

            }
            else
            {
                _sortDirection="DESC";
                dir = SortDirection.Ascending;

            }

            if (dt != null)
            {
                //Sort the data.
                dt.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
                gridView1.DataSource = dt;
                gridView1.DataBind();
            }

        }


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