.NET Framework Class Library
GridView..::.DataKeyNames Property

Updated: April 2009

Gets or sets an array that contains the names of the primary key fields for the items displayed in a GridView control.

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web (in System.Web.dll)
Syntax

Visual Basic (Declaration)
<TypeConverterAttribute(GetType(StringArrayConverter))> _
Public Overridable Property DataKeyNames As String()
Visual Basic (Usage)
Dim instance As GridView
Dim value As String()

value = instance.DataKeyNames

instance.DataKeyNames = value
C#
[TypeConverterAttribute(typeof(StringArrayConverter))]
public virtual string[] DataKeyNames { get; set; }
Visual C++
[TypeConverterAttribute(typeof(StringArrayConverter))]
public:
virtual property array<String^>^ DataKeyNames {
    array<String^>^ get ();
    void set (array<String^>^ value);
}
JScript
public function get DataKeyNames () : String[]
public function set DataKeyNames (value : String[])
ASP.NET
<asp:GridView DataKeyNames="value" />

Property Value

Type: array<System..::.String>[]()[]
An array that contains the names of the primary key fields for the items displayed in a GridView control.
Remarks

Use the DataKeyNames property to specify the field or fields that represent the primary key of the data source. You must set the DataKeyNames property in order for the automatic update and delete features of the GridView control to work. The values of these key fields are passed to the data source control in order to specify 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 access the primary keys of each row.

NoteNote:

The GridView control stores these key field values in the control state. If these values contain sensitive information, it is strongly recommended that you enable view-state encryption by setting the ViewStateEncryptionMode property to ViewStateEncryptionMode.Always.

When you use automatically generated field columns (by setting the AutoGenerateColumns property to true), the GridView control makes sure that the columns that correspond to the field or fields specified in the DataKeyNames property are read-only.

If the Visible property of a column field is set to false, the column is not displayed in the GridView control and the data for the column does not make a round trip to the client. If you want the data for a column that is not visible to be available to the client, add the field name to the DataKeyNames property.

TopicLocation
Walkthrough: Creating a Web Page to Display XML DataBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Creating a Web Page to Display XML DataBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Creating a Web Page to Display XML DataBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Displaying an XML Document in a Web Forms Page Using TransformationsBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Displaying an XML Document in a Web Forms Page Using TransformationsBuilding ASP .NET Web Applications in Visual Studio
Walkthrough: Displaying an XML Document in a Web Forms Page Using TransformationsBuilding ASP .NET Web Applications in Visual Studio
Examples

The following example demonstrates how to use the DataKeyNames property to specify the key field of the data source. In the example, the DataKeyNames attribute of the GridView element in markup specifies two key fields by using a comma to separate the names. To run this example, create a Web site that has the following:

  • A connection to the AdventureWorksLT sample database and a connection string that is named AdventureWorksLTConnectionString. You can download the AdventureWorksLT database from Microsoft SQL Server: Database Product Samples.

  • A LINQ-to-SQL data context class that is named AdventureWorksLTDataClassesDataContext. The data context must have a class for the SalesOrderDetails table. For information about how to create LINQ-to-SQL classes, see LINQ to SQL.

Visual Basic
<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
  <head runat="server">
    <title>GridView Edit Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>GridView Edit Example</h3>

      <!-- The GridView control automatically sets the columns     -->
      <!-- specified in the datakeynames property as read-only.    -->
      <!-- No input controls are rendered for these columns in     -->
      <!-- edit mode.                                              -->
      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        autogeneratedeletebutton="true"
        autogenerateeditbutton="true"
        datakeynames="CustomerID"  
        runat="server">
      </asp:gridview>

      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSqlDataSource"  
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        updatecommand="Update Customers SET CompanyName=@CompanyName, Address=@Address, City=@City, PostalCode=@PostalCode, Country=@Country WHERE (CustomerID = @CustomerID)"
        deletecommand="Delete from Customers where CustomerID = @CustomerID"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
        runat="server">
      </asp:sqldatasource>

    </form>
  </body>
</html>

C#
<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html  >
  <head runat="server">
    <title>GridView Edit Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>GridView Edit Example</h3>

      <!-- The GridView control automatically sets the columns     -->
      <!-- specified in the datakeynames property as read-only.    -->
      <!-- No input controls are rendered for these columns in     -->
      <!-- edit mode.                                              -->
      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="true"
        autogeneratedeletebutton="true"
        autogenerateeditbutton="true"
        datakeynames="CustomerID"  
        runat="server">
      </asp:gridview>

      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSqlDataSource"  
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        updatecommand="Update Customers SET CompanyName=@CompanyName, Address=@Address, City=@City, PostalCode=@PostalCode, Country=@Country WHERE (CustomerID = @CustomerID)"
        deletecommand="Delete from Customers where CustomerID = @CustomerID"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
        runat="server">
      </asp:sqldatasource>

    </form>
  </body>
</html>

Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0
See Also

Reference

Change History

Date

History

Reason

April 2009

Provided a new code example that shows how to specify multiple key fields.

Customer feedback.

Tags :


Community Content

Tom Dykstra - MSFT
Change log doesnt match content
The changelog says that it has been updated to show a multiple datakey's example but there is only a single example on the page and it contains one column in the datakeyname attribute.

[tdykstra]The revised example code can be seen in the .NET Framework 4.0 version of this page. It will be added to this page in the next release of the documentation.
Tags : cpubfix

Tom Dykstra - MSFT
Same issue
I have been trying for over week to take advantage of the DATAKEYNAME property of a Gridview and have had nothing but problems. It appears that the comma delimited field names are not passed to my stored procedure.

Please update this page with more relavant content to the use of these properties.

[tdykstra]The .NET Framework 4.0 version of this page for an example that uses comma-delimited names.
Tags : cpubfix

Page view tracker