我有一个页面允许对列进行排序以及过滤 GridView 数据的搜索选项。我遇到的问题是在通过“搜索”选项过滤数据表时,GridView 的 ViewState SortExpression 丢失了。
我的问题是如何在 DataBind 之后保留 ViewState 以确保 SortExpression 保留在新绑定(bind)的数据表上?
protected void Page_Load(object sender, EventArgs e)
{
try{
if (IsPostBack)
{
Control control = null;
string controlName = Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = FindControl(controlName);
GridViewRow gvRow1 = (GridViewRow)control.Parent.Parent;
string controlID = control.ID.ToString();
}
}
if(!IsPostBack)
{
DataGrid_Load(DAL.reg(HeadText.Text, OrgText.Text), "reg");
}
}
catch{}
}
private void DataGrid_Load(DataTable command, string type)
{
DataTable dataTable = new DataTable();
dataTable = command;
string sortDir = ViewState["SortDirection"] as string;
string sortExp = ViewState["SortExpression"] as string;
if(ViewState["SortExpression"] != null)
{
dataTable = resort(dataTable, sortExp, sortDir);
}
string myStatus = HeadText.Text;
DataRow[] dr = dataTable.Select("status = '" + myStatus + "'");
DataTable filteredDataTable = dataTable.Clone();
foreach (DataRow sourceRow in dr)
{
filteredDataTable.ImportRow(sourceRow);
}
GridView1.DataSource = filteredDataTable;
GridView1.DataBind();
}
public class dal
{
public DataTable reg(string head, string org = null)
{
if (head == "all")
return Data_Load(String.Format("SELECT * from reg"), "reg");
}
}
最佳答案
我解决了这个问题,这只是我的加载数据过程的一个问题,它没有考虑是否已经在 GridView 中过滤了一些东西,并且过滤器在新的加载中丢失了。
为了解决这个问题,我制作了一个静态 searchFilter 变量,并在每个调用将数据加载到 GridView 的方法中添加了检查:
- 列排序后
- “每页行数”更改后
- 该页面中需要在该页面上加载数据的任何其他功能。
代码在每个加载数据的函数中看起来是这样的:
if(searchFilter != "")
loadDataWithFilter();
else
loadDataWithoutFilter();
我不需要对 Page_Load PostBack 做任何事情。
关于c# - DataBind 后 GridView 丢失 ViewState "SortExpression",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49310432/