I try to get the Social security number (SSN) of the selected element from a gridview when the user selects a row.
<asp:GridView ID="PeopleGrid" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None"
onselectedindexchanged="GetDataForPerson" DataKeyNames="SSN">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowSelectButton="True" ButtonType="Button" SelectText="Select" />
<asp:BoundField HeaderText="NameHeader" DataField="NameProp" />
<asp:BoundField HeaderText="AddressHeader" DataField="PersAddressProp" />
</Columns>
protected void GetDataForPerson(object sender, EventArgs e)
{
va开发者_JS百科r x= PeopleGrid.SelectedDataKey.Value.ToString()
}
x should be the SSN of the selected person, but PeopleGrid.SelectedDataKey is null. What is wrong here?
This is how I bind the data:
PeopleGrid.DataSource = PeopleCollection;
PeopleGrid.DataBind();
PeopleCollection is a collection of People. Class people contains SSN, NameProp, PersAddressProp
if you want to find selected row "SSN" value then you need to use Gridview's DataKeys property, like GridView1.DataKeys["your_SelectedDataKey_index"]["your_selected_row_index"]. This is a read only property.
精彩评论