How to use the FilterExpression in your GridView

1st, Create a method that will apply the filter from a session state

private void ApplyFilter()
 {
   SqlDataSourceTitle.FilterExpression = Session[
"MyFilter"] as string;
}

 

2nd

Set the filter to blank in the initialization in Page_Load and call ApplyFilter every time in the post back

protected void Page_Load(object sender, EventArgs e)
{
 
if (!IsPostBack)
   {
        Session["MyFilter"] = "";
   
}
 
else
  
{
      ApplyFilter();
   }

}

3rd

Create a Method that will set the filter in the Session and apply the filter

protected void SetFilter(string filter)
 {
   Session[
"TitleFilter"] = filter;
   ApplyFilter();
 }

 

Call the SetFilter whenever you want to set the FilterExpression.  The FilterExpression will always be applied properly now in the postback.

Now things like Update and Delete in the GridView will work properly when using a FilterExpression

(sample filter expression call)

SetFilter ("firstname = 'Harry'")  where firstname is a field in your database bound to the grid.