Gridview SelectedIndexChanged Showing no Data
Selection is handled slightly differently than choosing an edit item, sorting, paging, or other functions: because those other functions require a change in the control tree or a query to the data source to get different data, they cause a DataBind to happen automatically at some point before the control renders again. You can handle RowDataBound and get your data item. Selection, however, doesn’t require new data or a different control tree (all that usually changes is the style properties on the row), so it will never call DataBind. This makes selection very fast. It also means you won’t get a DataBound or RowDataBound event unless you call DataBind yourself. So you can’t use that event to get your data item unless you call it yourself. If you need the data item, you can call DataBind yourself directly to get it, then handle OnRowDataBound, check the row index against the SelectedIndex, and get the data item.
However, this is kind of the shotgun method- it will get you what you want, but the performance has decreased because you’ve called DataBind again. Also, if the data in the data store has been modified between your calls to databind, the row index that was the selected item may now point to a different row or just different data. What data are you really looking for from the selected data item? Is it just one or two fields? If so, consider using DataKeyNames to store these fields, and then you can get to them via the DataKeys property. If you don’t want to suffer the hit to ViewState from DataKeyNames, consider getting the data directly from the controls in the row of the GridView.
So I followed the suggestion highlighted in yellow and was able to retrieve the value for the selected row.
Posted in ASP.NET Tagged: ASP.NET
This was originally posted here.

Like
Report
*This post is locked for comments