我的网格视图是手动数据绑定(其他工作)。读取其他线程我必须管理自己的排序事件。
点击列以在我的网页上对其进行排序时,我收到错误:
“对象引用未设置为对象的实例。”
这样做的结果是该表为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;
}
感谢。
答案 0 :(得分:1)
DataTable table = BuildInfo_GridView.DataSource as DataTable;
像这样你不会得到数据源你已经绑定的回调结束查询来获取数据,或者当你绑定数据时只将它存储在视图状态并获取它
答案 1 :(得分:0)
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();
}