繁体   English   中英

GridView在DataBind之后丢失ViewState“ SortExpression”

[英]GridView loses ViewState “SortExpression” after DataBind

我有一个页面,它既可以对列进行排序,也可以对GridView数据进行过滤的搜索选项。 我遇到的问题是,通过“搜索”选项过滤数据表时,GridView的ViewState SortExpression丢失了。

我的问题是如何在DataBind之后保留ViewState以确保SortExpression保留在新绑定的dataTable上?

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中是否已经过滤了某些东西,而新的Load丢失了过滤器。

为了解决这个问题,我制作了一个静态searchFilter变量,并在每个要求将数据加载到GridView的方法中对此进行了检查:

  • 列排序后
  • 更改“每页行数”后
  • 该页面内需要在该页面上加载数据的任何其他功能。

代码在加载数据的每个函数中都这样看:

if(searchFilter != "")
    loadDataWithFilter();
else 
    loadDataWithoutFilter();

我不必对Page_Load PostBack做任何事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM