There are many times you may need to fetch the primary key field values for grid items. You can use the DataKeyNames and DataKeyValues arrays
of the GridTableView object for this purpose. When you specify a primary key field by adding it to the DataKeyNames array, the value of the
specified column becomes available in DataKeyValues array.
The following example illustrates this use of DataKeyNames and DataKeyValues. The ItemCommand and
SelectedIndexChanged event handlers use the DataKeyValues array to access the primary key of a row when it enters edit mode or when it is
selected, respectively:
| [ASP.NET] Grid with DataKeyNames set |
Copy Code |
|
<telerik:RadGrid
ID="RadGrid1" runat="server"
DataSourceID="AccessDataSource1"
AutoGenerateColumns="false"
OnItemCommand="RadGrid1_ItemCommand"
OnSelectedIndexChanged="RadGrid1_SelectedIndexChanged">
<MasterTableView
DataKeyNames= "CustomerID"
DataSourceID="AccessDataSource1">
<Columns>
<telerik:GridButtonColumn
CommandName="Select"
Text="Select"
UniqueName="SelectColumn"
/>
<telerik:GridBoundColumn
UniqueName="ContactName"
HeaderText="Contact name"
DataField="ContactName"
/>
<telerik:GridBoundColumn
UniqueName="ContactTitle"
HeaderText="Contact title"
DataField="ContactTitle"
/>
<telerik:GridBoundColumn
UniqueName="Address"
HeaderText="Address"
DataField="Address"
/>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:AccessDataSource
ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/Nwind.mdb"
SelectCommand="SELECT TOP 10 CustomerID, ContactName, ContactTitle,
Address FROM Customers">
</asp:AccessDataSource>
|
The event handlers use DataKeyValues:
| [C#] Using DataKeyValues |
Copy Code |
|
protected void RadGrid1_ItemCommand(object
source, Telerik.Web.UI.GridCommandEventArgs e)
{
if (e.CommandName == RadGrid.EditCommandName)
{
Response.Write("Primary key for the clicked item from ItemCommand: " +
e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["CustomerID"] + "<br>");
}
} protected void RadGrid1_SelectedIndexChanged(object sender, System.EventArgs e)
{
Response.Write("Primary key for the clicked item from SelectedIndexChanged: "
+ RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex][ "CustomerID"] + "<br>");
}
|
| [VB] Using DataKeyValues |
Copy Code |
|
Protected Sub RadGrid1_ItemCommand(ByVal source As Object, _
ByVal e As Telerik.Web.UI.GridCommandEventArgs) _
Handles RadGrid1.ItemCommand
If (e.CommandName = RadGrid.EditCommandName) Then
Response.Write("Primary key for the clicked item from ItemCommand: " _
+ e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("CustomerID") + "<br>")
End If
End Sub
Protected Sub RadGrid1_SelectedIndexChanged(ByVal sender
As Object, _
ByVal e As System.EventArgs)
Handles RadGrid1.SelectedIndexChanged
Response.Write("Primary key for the clicked item from SelectedIndexChanged: " _
+ RadGrid1.SelectedItems(0).OwnerTableView.DataKeyValues(RadGrid1.SelectedItems(0).ItemIndex)("CustomerID") +
"<br>")
End Sub
|