手动栅格视图排序
本文关键字:视图 排序 | 更新日期: 2023-09-27 17:49:19
我的网格视图是手动数据绑定的(用于其他工作(。阅读其他线程时,我必须管理自己的排序事件。
当点击一个列在我的网页上排序时,我会得到错误:
"对象引用未设置为对象的实例。">
这样做的结果是表为null,但我不明白为什么它为null。
有什么想法吗?
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;
}
谢谢。
DataTable table = BuildInfo_GridView.DataSource as DataTable;
像这样,你不会得到数据源,你已经绑定了回调查询来获得数据表,或者当你绑定数据时,只将其存储在视图状态并获得
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();
}