System.Web.UI.WebControls Namespace GridView Class
.NET Framework version 2.0
Sets or retrieves the names of the primary key fields in the data source bound to the GridView control.
Inline |
<asp:gridview datakeynames = strField1, strField2 ... > |
Script |
GridView.DataKeyNames [ = strField1, strField2 ... ] |
strField1, strField2 |
An array specifying the names of the primary key fields in the data source bound to the GridView control. |
The property is read/write with no default value.
NOTE: The specified field or fields must contain unique values ( no duplicate entries ).
Use the DataKeyNames property to specify the field or fields in the data source bound to the GridView control that will be used as the key column or columns that serve to uniqely identify each record.
NOTE: The DataKeyNames property is required when using the automatic updating and deleting features of the GridView control. The values of these key fields are passed to the data source control in order to match the row to update or delete.
When the DataKeyNames property is set, the GridView control automatically populates its DataKeys collection with the values from the specified field or fields, which provides a convenient way to store and retrieve the primary keys of each row, without having to display it in the control.
The GridView provides several properties for retrieving the selected item in the DataKeys collection.
- the SelectedValue property retrieves the data key value for the currently selected row directly.
- the SelectedDataKey property retrieves the DataKey object for the currently selected row.
- the SelectedIndex property retrieves the selected row index which can be used to retrieve the DataKey object at that index.
The key field is commonly used in a handler for an event, such as the SelectedIndexChanged event, where the value of the key field is used to build the SQL Select or Update query to retrieve and/or revise a specific record in the data source. The key field simplifies identifying the appropriate record to display or modify.
The following examples demonstrate how to set the DataKeyNames property to enable identifying the record selected by the user from a GridView control.
GridView Members DataKeys