【问题标题】:Manual Grid View Sorting手动网格视图排序
【发布时间】:2014-03-09 12:36:18
【问题描述】:

我的网格视图是手动数据绑定的(为了其他工作)。阅读其他线程我必须管理自己的排序事件。

在我的网页上单击列对其进行排序时,出现错误:

“对象引用未设置为对象的实例。”

结果是该表为空,但我不明白为什么它为空。

有什么想法吗?

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    DataTable table = GetData();
    table.DefaultView.Sort = e.SortExpression + " " + SetSortDirection(e.SortDirection.ToString());
    GridView1.DataSource = table;
    GridView1.DataBind();
}

.

protected string SetSortDirection(string currentsortDirection)
{
    string sortDirection;
    if (currentsortDirection == "Ascending")
    {
        sortDirection = "Descending";
    }
    else
    {
        sortDirection = "Ascending";
    }
    return sortDirection;
}

编辑:

public DataTable GetData()
{
    SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True");
    conn.Open();
    string query = "SELECT * FROM tablex WHERE Property='" + Request.QueryString["xxx"] + "'";
    SqlCommand cmd = new SqlCommand(query, conn);

    DataTable dt = new DataTable();
    dt.Load(cmd.ExecuteReader());
    return dt;
}

谢谢。

【问题讨论】:

  • 请调试您的应用程序并查看BuildInfo_GridView.DataSource的值

标签: c# asp.net sorting gridview


【解决方案1】:
 DataTable table = BuildInfo_GridView.DataSource as DataTable;

像这样你不会得到你已经绑定的数据源调用后端查询来获取数据表,或者当你绑定数据时只将它存储在视图状态并获取它

【讨论】:

  • 您好,感谢您的回复。我已经更新了我的问题,使用当前代码我只能以一种方式排序,所以当我分配数据时,无论我做什么,它都会说 e.SortDirection="Ascending"。
【解决方案2】:
Save your sort order in view state
if (ViewState["sortOrder"] != null)
            {
                ViewState["sortExpression"] = e.SortExpression;
                if (ViewState["sortOrder"].ToString().ToUpper() == "ASCENDING")
                {
                    e.SortDirection = SortDirection.Descending;
                    ViewState["sortOrder"] = SortDirection.Descending.ToString();
                }
                else
                {
                    e.SortDirection = SortDirection.Ascending;
                    ViewState["sortOrder"] = SortDirection.Ascending.ToString();
                }
            }
            else
            {
                ViewState["sortExpression"] = e.SortExpression;
                ViewState["sortOrder"] = e.SortDirection.ToString();
            }

【讨论】:

    猜你喜欢
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多