Search code examples
gridviewcode-behind

Update GridView after a re-order


I have a gridview reliant on three cascading dropdowns (in an updatepanel). When the user edits a cell in the gridview, changes a dropdown, and clicks 'Display' it calls the following codebehind:

protected void Save_Click(Object sender, EventArgs e)
    {
        foreach (GridViewRow gvr in MasterDisplay.Rows)
            MasterDisplay.UpdateRow(gvr.RowIndex, false);
        MasterDisplay.DataBind();
}

The problem is that the dropdowns will change the gridview, so the updated cells get out of order. An example: Let's say I have six items: A1, A2, A3, B1, B2, B3. If I edit price for B2, then change the dropdown that says 'show Bs first', on the resulting page I'll see the new price for A2 instead (ie, whatever is fifth in the order).

I figure this is because in UpdateRow() we're only updating based on the index (gvr.RowIndex), so somehow the GridView is getting redisplayed (without losing the new price data!) and then updated.

Any ideas on how to ensure that these changes save to the appropriate row, rather than just the row that happens to now have the same index as previously?


Solution

  • So, as is becoming common, I guess I'll answer my own question in case one day someone stumbles upon this. (ie http://xkcd.com/979/)

    Basically, I created three labels that are fed variables from Request.QueryString on Page_Load (where the variables are passed in the url). These labels are now the ControlParameters for the SqlDataSource building the gridview. I also fill the dropdowns from this variable. ie

    var myInternalVar1 = Request.QueryString["myVariable1"];
    myLabel1.Text = myInternalVar1;
    myDropDown1.SelectedValue = myInternalVar1;
    

    Then the user can use dropdowns as normal (from their end). When the user clicks save, I run the current code (see question) and then add:

    myLabel1.Text = myDropDown1.SelectedValue;
    Response.Redirect("~/mysite.aspx?myVariable1=" + myLabel1.Text);
    

    This means no more postbacks, but instead navigation.

    One important note: I had to fill all dropdowns in if(!Page.IsPostBack) because the pre-existing functions I piggybacked on seemed to be getting called multiple times. Not sure why they were called since they were only in one declaration ( got called three times after dropdown was used, even though outside gridview is outside updatepanel)