简体   繁体   中英

GridView loses ViewState “SortExpression” after DataBind

I have a page that allows both sorting columns as well as a search option that filters the GridView data. The problem I am running into is the GridView's ViewState SortExpression gets lost when filtering the datatable through the Search option.

My question is how do I retain the ViewState after a DataBind to ensure the SortExpression is kept on the newly binded 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");
    }
}

I resolved this and it was simply a problem with my Load Data procedure which did not take into account if there was something already filtered in the GridView and the filter was being lost on the new Load.

To fix this I made a static searchFilter variable and added a check for this in each of the methods that called for loading data into the GridView:

  • after column sorting
  • after the "Rows Per Page" is changed
  • Any other functions within that page that require Loading Data on that page.

The code looked this this in each of the functions that load data:

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

I did not have to do anything with the Page_Load PostBack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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