I have the following code to evaluate the value of a cell once a row is selected in a GridView. It works fine if the cell is text, but need to evaluate a cell that is a number and would like to return it to the detailsLabel. How should I modify this code to do that:
Dim selectedRowIndex As Integer
selectedRowIndex = gridDepts.SelectedIndex
Dim row As GridViewRow = gridDepts.Rows(selectedRowIndex)
Dim name As String = row.Cells(0).Text
detailsLabel.Text = "You selected " & name & “.”
I was able to resolve this question, so I thought I would share it.
I needed to get the value and not the text of a selected cell, so I modified the GridView to include a DataKeyNames property like so:
<asp:GridView ID=“gridDepts” AutoGenerateColumns=“false”
runat=“server”
CellPadding=“4”
GridLines=“None”
CssClass=“GridMain” DataKeyNames=“DEPARTMENT_CODE”>
<RowStyle CssClass=“GridRow” />
<SelectedRowStyle CssClass=“GridSelectedRow” />
<HeaderStyle CssClass=“GridHeader” />
<Columns>
<asp:ButtonField CommandName=“Select” DataTextField=“DEPARTMENT_CODE” HeaderText=“Dept. #” />
<asp:BoundField DataField=“DEPARTMENT_DESC” HeaderText=“Department” />
</Columns>
</asp:GridView>
DEPARTMENT_CODE had the value that I was attempting to return. So now I added the code to get the selected value from the cell by writing the following code:
Protected Sub gridDepts_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles gridDepts.SelectedIndexChanged
Dim selectedRowIndex As Integer
selectedRowIndex = gridDepts.SelectedIndex
Dim row As GridViewRow = gridDepts.Rows(selectedRowIndex)
Dim name As String = gridDepts.SelectedDataKey.Value.ToString()
detailsLabel.Text = "You selected " & name & "."
End Sub
Here is where I found help on this topic: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeys.aspx
Hope this helps if you run into the same issue. If you have a question about this post, you can message me here or contact me directly on twitter at: https://twitter.com/ChrisSergent
Chris