Search code examples
c#gridviewasp.net-controls

Gridview sorting doesn't fire in first click


I have the following two controls in my code

gridview (for data display) sqldatasource (source of my gridview)

I want to change the gridview, but when I change the sqlcommandstring in my sqldatasource, in new view of my datagrid table sorting doesn't fire for the first click. Please see below for sqlcommandstring change process.

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack)
            {   // Restore saved sqlcommand in page refresh, please see below
                SqlDataSource1.SelectCommand = ViewState["MySQL"].ToString();
            }
        }
        catch (Exception ex){}            
    }

    protected void btn_SearchLibrary_Click(object sender, EventArgs e)
    {
        SqlDataSource1.SelectCommand = "SELECT * FROM Books WHERE id=1 OR id=2";
        ViewState["MySQL"] = "SELECT * FROM Books WHERE id=1 OR id=2";
        //Saves sqlcommand in viewstate, to restore it in page refresh.
    }

Solution

  • I believe the DataBinding of your GridView is happening before the Click event handler for your button. Therefore, your grid has already been updated from the data source before the data source itself is changed. After updating the SelectCommand in your Click event handler, you would have to explicitly call DataBind for the grid.
    Also, as an aside, it looks like your try-catch in your Page_Load is just to suppress the NullReferenceException, since Page_Load also fires before the Click event handler, so ViewState["MySQL"] is always going to be null at first.