Wednesday, January 07, 2009

Getting the changed data from a GridView in the RowUpdating event

Ah! the good old problem of getting the data from the row that is being currently edited within a GridView.

Obviously the simplest method is to use DataKeyNames on the GridView and then you should have the data in your GridViewUpdateEventArgs as part of e.NewValues.

But e.NewValues and e.OldValues dont always get a value. This can happen for a number of reasons. In my case this was happening because I was binding to a List of custom objects.

There are multiple ways in which one can get the data from the current row that is being edited in a GridView.

1. Using "ExtractValuesFromCell": This is an easy way to get all the values from the current row. As the values are inserted into an OrderedDictionary - you can use the field names to access the changed data odNew.

OrderedDictionary odNew = new OrderedDictionary();
        for (int colIndex = 0; colIndex < gridView.Columns.Count; colIndex++ )
        {
            DataControlRowState dcrState = DataControlRowState.Normal;
            DataControlFieldCell cell = gridView.Rows[e.RowIndex].Cells[colIndex] as DataControlFieldCell;
            gridView.Columns[colIndex].ExtractValuesFromCell(odNew, cell, dcrState, true);
        }

2. Accessing the "Controls": This method gets you access to the control in the GridView, which might be useful based on what you are doing. (In the following example, I cast to a CheckBox as I know I have a checkbox at the colIndexYouAreInterestedIn - you should cast to whatever control you have in that column).

CheckBox checkBoxAllowView = gridView.Rows[e.RowIndex].Cells[colIndexYouAreInterestedIn].Controls[0] as CheckBox;

Note
A common mistake that a lot of people do is that they perform a databind each and every-time the Page_Load method is called. This will lead to problems like "GridView does not show updated values", "GridView looses values changed by user". Perform your databinding only when you have to. In your Page_load, this is typically only inside a block where you check to make sure that Page_Load is not being called during a post-back call.

1 comment:

Anthony L. Burns, Esq. said...

Thank you so much - brilliant point - there are millions of useless posts on this issue - your point about the databinding was very appreciated - to bad newvalues still doesn't seem to work