Access a value using SelectedIndexChanged() event when a row in a GridView control is selected

There are many instances when the value in a cell is required. For example, when we need to display more information about the selected row. This example demonstrates how access a value in a GridView cell from the selected row using SelectedIndexChanged() event.



<asp:gridview id="ItemsGridView" datasourceid="MyDataSource" 
autogeneratecolumns="true" autogenerateselectbutton="true" allowpaging="true" 
selectedindex="0" onselectedindexchanged="ItemsGridView_SelectedIndexChanged"
OnSelectedIndexChanging="ItemsGridView_SelectedIndexChanging"   
runat="server">
<selectedrowstyle backcolor="BlanchedAlmond" forecolor="DarkBlue" 
BorderColor="Beige" BorderStyle="Dotted" BorderWidth="3" 
Font-Size="Medium" font-bold="true"/>  
</asp:gridview>

In the given code, the method 'OnSelectedIndexChanged' of the GridView control is assigned to the event handler ItemsGridView_SelectedIndexChanged.

<asp:label id="Message"    forecolor="Red"    runat="server"/>
<asp:SqlDataSource ID="MyDataSource"  
ConnectionString="<%$Connectionstrings:ERPConnectionString%>"
SelectCommand="SELECT ItemID,ItemName,ItemType,ClStk FROM ItemTable" 
runat="server"/>

screen
The SelectedIndexChanged event is raised when a row's Select button is clicked. We use the SelectedIndexChanged eventhandling method to display the currently selected row. Using the SelectedRow property, we get the currently selected row in the gridView control. Then, we access the data in the cells of the row using the statement:

row.Cells[2].Text

The above statement displays the value in the third cell of the row.

The following code is the event handler for the SelectedIndexChanged event.

<asp:gridview id="ItemsGridView" datasourceid="MyDataSource" 
autogeneratecolumns="true" autogenerateselectbutton="true" allowpaging="true" 
selectedindex="0" onselectedindexchanged="ItemsGridView_SelectedIndexChanged"
OnSelectedIndexChanging="ItemsGridView_SelectedIndexChanging"   
runat="server">
<selectedrowstyle backcolor="BlanchedAlmond" forecolor="DarkBlue" 
BorderColor="Beige" BorderStyle="Dotted" BorderWidth="3" 
Font-Size="Medium" font-bold="true"/>  
</asp:gridview>