GridView.DataKeyNames 属性

获取或设置一个数组,该数组包含了显示在 GridView 控件中的项的主键字段的名称。

 

C#
public virtual string[] DataKeyNames { get; set; }

 

 

属性值

一个数组,其中包含了显示在 GridView 控件中的项的主键字段的名称。

使用 DataKeyNames 属性指定表示数据源主键的字段。

Note注意

若要以声明方式设置此属性,请使用以逗号分隔的字段名列表。

当设置了 DataKeyNames 属性时,GridView 控件用来自指定字段的值填充它的 DataKeys 集合,这提供了一种访问每个行的主键的便捷方法。

Note注意

GridView 控件以控件状态存储这些键字段值。如果这些值包含敏感信息,则强烈建议您通过将 ViewStateEncryptionMode 属性设置为 ViewStateEncryptionMode.Always 来启用视图状态加密。

在使用自动生成的字段列时(通过将 AutoGenerateColumns 属性设置为 true),GridView 控件自动确保与 DataKeyNames 属性中指定的字段相对应的自动生成字段列是只读的。

Note注意

为了使 GridView 控件的自动更新和删除功能工作,必须设置 DataKeyNames 属性。为了匹配要更新或删除的行,这些键字段的值被传递到数据源控件。

如果将某个列字段的 Visible 属性设置为 false,则在 GridView 控件中将不显示该列,该列中的数据也不会往返于客户端。如果希望某个不可见的列中的数据可以进行往返,则向 DataKeyNames 属性添加相应的字段名称。

 

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

<html>
  <body>
    <form 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>

 

posted @ 2009-04-17 11:00  minmin8110  阅读(628)  评论(0)    收藏  举报