Why GridView RowUpdating Event is not giving the updated values?

Debugger Inside GridView RowUpdating Event

Debugger Inside GridView RowUpdating Event


This is a most common question in Forums. We will find the actual cause, for which the RowUpdating Event behaves abnormal.

Walk Through

  1. Add a GridView in aspx page and define all its required properties and Events.
    <asp:GridView ID="gvTestGrid" runat="server" AutoGenerateColumns="false" 
                  OnRowCancelingEdit="gvTestGrid_RowCancelingEdit"
                  OnRowEditing="gvTestGrid_RowEditing" 
                  OnRowUpdating="gvTestGrid_RowUpdating">
        <Columns>
            <asp:BoundField DataField="Column1" HeaderText="Some Column"/>
            <asp:CommandField ShowEditButton="true" />
        </Columns>
    </asp:GridView>
    
  2. Bind the GridView from back end. For our example, we will bind one DataTable.
    private void BindGrid()
    {
        // Add Column for the DataTable.
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Column1"));
    
        // Add Rows to DataTable.
        for (int i = 1; i < 5; i++)
        {
    	    DataRow dr = dt.NewRow();
    	    dr["Column1"] = "Old Value" + i;
    	    dt.Rows.Add(dr);
        }
    
        gvTestGrid.DataSource = dt;
        gvTestGrid.DataBind();
    }
  3. Define the GridView Events for Edit and Update operation.
    protected void gvTestGrid_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //Set the edit index.
        gvTestGrid.EditIndex = e.NewEditIndex;
    
        //Bind data to the GridView control.
        BindGrid();
    }
    
    protected void gvTestGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //Get the new Values.
        GridViewRow row = gvTestGrid.Rows[e.RowIndex];
        string column1Value = ((TextBox)row.Cells[0].Controls[0]).Text;
    
        // Code to update the DataSource.
        //.....
    
        //Reset the edit index.
        gvTestGrid.EditIndex = -1;
    
        //Bind data to the GridView control.
        BindGrid();
    }
    
    protected void gvTestGrid_RowCancelingEdit(object sender, 
                                               GridViewCancelEditEventArgs e)
    {
        //Reset the edit index.
        gvTestGrid.EditIndex = -1;
    
        //Bind data to the GridView control.
        BindGrid();
    }
    
  4. GridView on Browser would look like…

    GridView on Browser

    GridView on Browser

    Now, Let’s Test

    To test the Edit and Update features, let’s click on Edit Button in any Row. We can see that GridView adds TextBoxes in all the cells of that Row immediately. It also shows you Update and Cancel Buttons where it was previously showing Edit Button.
    Let’s do some editing in the cells and click Update Button.

    GridView Cell Showing Updated Value

    GridView Cell Showing Updated Value


    It hits the breakpoint, we have set inside the RowUpdating Event. If we move our mouse on to the variables, which hold the cell values, we can see the old value instead of new updated value (Refer the debugging Screen Shot at the Top). So, we are stuck now, this is the bug.

    What to do now?

    Don’t panic. We need to find out what exactly in code is helping RowUpdating Event to give old values. So, the most wild guess is that, something is causing the Grid to bind again before RowUpdating Event, as we initially did during load.

    If you remember, in Step-2, we did bind the Grid, which is actually called on the Page Load like…

    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }
    

    According to the Event Life Cycle, when any Control Event is fired (here Grid RowUpdating), it first goes to Page Load. As it is coming to Page Load, so it calls the Bind method again and re-binds the Grid. Now, it goes to RowUpdating Event, but the updated values are lost because Grid is already reset in Page Load.

    So, How to Resolve?

    IsPostBack() is the answer. We have to check if the Page is posted back or not. If not, then we will bind the Grid.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    

    Go and Share this with your friends

    This issue sometimes kills time. So, don’t wait, just share with everybody you know, who can understand this. Also provide your valuable feedback here. Thanks for reading.

Why DropDownList SelectedValue not working inside SelectedIndexChanged Event?

Debugger Inside DropDown SelectedIndexChanged Event

Debugger Inside DropDown SelectedIndexChanged Event


In this Blog, we will explore one interesting Bug, which ASP.NET Developers encounter sometimes.

Bug

DropDownList SelectedValue inside SelectedIndexChanged Event does not give the current Selected Value, rather it gives the Default Value or first Option Value.

Walk Through

  1. Let’s declare a DropDownList first.
    <asp:DropDownList ID="ddlDropDownId" runat="server" AutoPostBack="true" 
                      OnSelectedIndexChanged="ddlDropDownId_SelectedIndexChanged">
    </asp:DropDownList>
    
  2. Now to bind the DropDownList, we will write one function like below…
    private void BindDropDownList()
    {
        // Declare a Dictionary to hold all the Options with Value and Text.
        Dictionary<string, string> options = new Dictionary<string, string>();
        options.Add("-1", "Select Option");
        options.Add("1", "Option 1");
        options.Add("2", "Option 2");
        options.Add("3", "Option 3");
        options.Add("4", "Option 4");
        options.Add("5", "Option 5");
    
        // Bind the Dictionary to the DropDownList.
        ddlDropDownId.DataSource = options;
        ddlDropDownId.DataTextField = "value";
        ddlDropDownId.DataValueField = "key";
        ddlDropDownId.DataBind();
    }
    
  3. So, when you run the Page, it would show you the DropDownList on the Page with the Options defined.
    DropDownList on Browser

    DropDownList on Browser

  4. When you select an Option from the DropDownList, it hits the SelectedIndexChanged Event in the Code Behind. If you need to get the SelectedValue, then you will write…
    protected void ddlDropDownId_SelectedIndexChanged(object sender, EventArgs e)
    {
        string value = ddlDropDownId.SelectedValue;
    }
    
  5. Now Here Comes the Main Issue

    When we put a debugger inside the Event and checked, irrespective of the selection of any Option, it always gives you the first Option Value that is “-1”. Refer the debugging Screen Shot at the Top.
    And there is no doubt on the first Option value “-1”, as we can clearly see from the Source HTML of the DropDownList. See highlighted Option in the image below.

    DropDownList Source HTML

    DropDownList Source HTML

    Any Hint Here?

    As we are getting the default value or the first value always, so the guess is that, something is causing the DropDownList to bind again when we select an Option.

    Let’s Find Out !!!

    In the Walk Through Steps, I said about the function BindDropDownList(), which binds the DropDownList. But we need to check where exactly it is getting called. As the DropDownList shows when the Page is Loaded, so it must be present inside the Page Load Event.

    protected void Page_Load(object sender, EventArgs e)
    {
        BindDropDownList();
    }
    

    Now, according to the Event Life Cycle rules, when you select an Option from DropDownList, it Posts Back and goes to Page Load Event first and then it comes to the SelectedIndexChanged Event.
    That means, it comes to the Page Load again on selection of any Option and calls the BindDropDownList(). Thus, the DropDownList is bounded again, before it goes to the SelectedIndexChanged Event. As the DropDownList is bound again, so the SelectedValue is now the first Option Value, which is “-1” (for “Select Option”).

    Fix?

    You might have got the answer. That is IsPostBack Property.

    Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.

    It tells you whether you are loading the Page for first time or is it a Post Back due to any Event. Modified code would look something like below.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDownList();
        }
    }
    

    So, Be Careful and Share This to Save Someone’s Day !!!

    You might have played with all the codes in your Page to find out the issue, but at last you come to know that it was because you forgot to check IsPostBack Property. So, Like and Share this with your friends, so that anybody who is unable to find the problem, finally let out a sigh.