GridView.SelectedDataKey Właściwość

Definicja

DataKey Pobiera obiekt zawierający wartość klucza danych dla wybranego wiersza w kontrolceGridView.

public:
 virtual property System::Web::UI::WebControls::DataKey ^ SelectedDataKey { System::Web::UI::WebControls::DataKey ^ get(); };
[System.ComponentModel.Browsable(false)]
public virtual System.Web.UI.WebControls.DataKey SelectedDataKey { get; }
[<System.ComponentModel.Browsable(false)>]
member this.SelectedDataKey : System.Web.UI.WebControls.DataKey
Public Overridable ReadOnly Property SelectedDataKey As DataKey

Wartość właściwości

Element DataKey dla zaznaczonego wiersza w kontrolce GridView . Wartość domyślna to null, co oznacza, że obecnie nie wybrano żadnego wiersza.

Atrybuty

Wyjątki

W właściwości nie określono DataKeyNames kluczy danych.

Przykłady

W poniższym przykładzie pokazano, jak za pomocą SelectedDataKey właściwości określić wartość klucza danych wybranego wiersza w kontrolce GridView .


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)  
  {
        
    // Display the primary key value of the selected row.
    Message.Text = "The primary key value of the selected row is " +
      CustomersGridView.SelectedDataKey.Value.ToString() + ".";
    
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridView SelectedDataKey Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridView SelectedDataKey Example</h3>
            
      <asp:label id="Message"
        forecolor="Red"
        runat="server"/>
                
      <br/><br/>

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSource" 
        allowpaging="true"
        autogeneratecolumns="true"
        autogenerateselectbutton="true"    
        datakeynames="CustomerID"
        onselectedindexchanged="CustomersGridView_SelectedIndexChanged"   
        runat="server">
                
        <selectedrowstyle backcolor="LightBlue"
          forecolor="DarkBlue"/> 
               
      </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="CustomersSource"
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
            
    </form>
  </body>
</html>

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Sub CustomersGridView_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        
    ' Display the primary key value of the selected row.
    Message.Text = "The primary key value of the selected row is " & _
      CustomersGridView.SelectedDataKey.Value.ToString() & "."
    
  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridView SelectedDataKey Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridView SelectedDataKey Example</h3>
            
      <asp:label id="Message"
        forecolor="Red"
        runat="server"/>
                
      <br/><br/>

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSource" 
        allowpaging="true"
        autogeneratecolumns="true"
        autogenerateselectbutton="true"    
        datakeynames="CustomerID"
        onselectedindexchanged="CustomersGridView_SelectedIndexChanged"   
        runat="server">
                
        <selectedrowstyle backcolor="LightBlue"
          forecolor="DarkBlue"/> 
               
      </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="CustomersSource"
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
            
    </form>
  </body>
</html>

W poniższym przykładzie pokazano, jak użyć drugiego pola klucza jako parametru w scenariuszu głównym/szczegółowym. Kontrolka GridView służy do wyświetlania rekordów z tabeli Order Details bazy danych Northwind. Po wybraniu rekordu w kontrolce GridView szczegóły produktu z tabeli Products są wyświetlane w kontrolce DetailsView . ProductID to druga nazwa klucza w kontrolce GridView . Aby uzyskać dostęp do drugiego klucza, wartość GridView1.SelectedDataKey[1] jest używana jako PropertyNameControlParameter obiekt SqlDataSource kontrolki DetailsView .


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>Selecting Data Key Values</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:SqlDataSource 
      ID="SqlDataSource1" 
      runat="server" 
      ConnectionString="<%$ ConnectionStrings:NorthWindConnectionString%>"
      ProviderName="System.Data.SqlClient" 
      SelectCommand="SELECT * FROM [Order Details]">
    </asp:SqlDataSource>

    <asp:SqlDataSource 
      ID="SqlDataSource2" 
      runat="server" 
      ConnectionString="<%$ ConnectionStrings:NorthWindConnectionString%>"
      ProviderName="System.Data.SqlClient" 
      SelectCommand="SELECT * FROM [Products]WHERE [ProductID] = @productid">
      <SelectParameters>
        <asp:ControlParameter 
          Name="productid" 
          ControlID="GridView1" 
          PropertyName="SelectedDataKey[1]" />
      </SelectParameters>
    </asp:SqlDataSource>
    
  </div>

  <asp:GridView 
    ID="GridView1" 
    runat="server" 
    AllowPaging="True" 
    AutoGenerateColumns="False"
    DataKeyNames="OrderID,ProductID" DataSourceID="SqlDataSource1">
    <Columns>
      <asp:CommandField ShowSelectButton="True" />
      <asp:BoundField DataField="OrderID" HeaderText="OrderID" ReadOnly="True"/>
      <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" />
      <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />
      <asp:BoundField DataField="Quantity" HeaderText="Quantity" />
      <asp:BoundField DataField="Discount" HeaderText="Discount" />
      </Columns>
    </asp:GridView>
    <br />
    <asp:DetailsView 
      ID="DetailsView1" 
      runat="server" 
      AutoGenerateRows="False" 
      DataKeyNames="ProductID"
      DataSourceID="SqlDataSource2" 
      Height="50px" Width="125px">
      <Fields>
        <asp:BoundField 
          DataField="ProductID" 
          HeaderText="ProductID" 
          InsertVisible="False"
          ReadOnly="True" />
        <asp:BoundField DataField="ProductName" HeaderText="ProductName"/>
        <asp:BoundField DataField="SupplierID" HeaderText="SupplierID"/>
        <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
        <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" />
        <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />
        <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" />
        <asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" />
        <asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel" />
        <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" />
      </Fields>
    </asp:DetailsView>
  </form>
</body>
</html>

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title>Selecting Data Key Values</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:SqlDataSource 
      ID="SqlDataSource1" 
      runat="server" 
      ConnectionString="<%$ ConnectionStrings:NorthWindConnectionString%>"
      ProviderName="System.Data.SqlClient" 
      SelectCommand="SELECT * FROM [Order Details]">
    </asp:SqlDataSource>

    <asp:SqlDataSource 
      ID="SqlDataSource2" 
      runat="server" 
      ConnectionString="<%$ ConnectionStrings:NorthWindConnectionString%>"
      ProviderName="System.Data.SqlClient" 
      SelectCommand="SELECT * FROM [Products]WHERE [ProductID] = @productid">
      <SelectParameters>
        <asp:ControlParameter 
          Name="productid" 
          ControlID="GridView1" 
          PropertyName="SelectedDataKey[1]" />
      </SelectParameters>
    </asp:SqlDataSource>
    
  </div>

  <asp:GridView 
    ID="GridView1" 
    runat="server" 
    AllowPaging="True" 
    AutoGenerateColumns="False"
    DataKeyNames="OrderID,ProductID" DataSourceID="SqlDataSource1">
    <Columns>
      <asp:CommandField ShowSelectButton="True" />
      <asp:BoundField DataField="OrderID" HeaderText="OrderID" ReadOnly="True"/>
      <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" />
      <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />
      <asp:BoundField DataField="Quantity" HeaderText="Quantity" />
      <asp:BoundField DataField="Discount" HeaderText="Discount" />
      </Columns>
    </asp:GridView>
    <br />
    <asp:DetailsView 
      ID="DetailsView1" 
      runat="server" 
      AutoGenerateRows="False" 
      DataKeyNames="ProductID"
      DataSourceID="SqlDataSource2" 
      Height="50px" Width="125px">
      <Fields>
        <asp:BoundField 
          DataField="ProductID" 
          HeaderText="ProductID" 
          InsertVisible="False"
          ReadOnly="True" />
        <asp:BoundField DataField="ProductName" HeaderText="ProductName"/>
        <asp:BoundField DataField="SupplierID" HeaderText="SupplierID"/>
        <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
        <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" />
        <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />
        <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" />
        <asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" />
        <asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel" />
        <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" />
      </Fields>
    </asp:DetailsView>
  </form>
</body>
</html>

Uwagi

Po ustawieniu DataKeyNames właściwości kontrolka GridView automatycznie tworzy DataKey obiekt dla każdego wiersza w kontrolce przy użyciu wartości lub wartości określonego pola lub pola. Obiekty DataKey są następnie dodawane do kolekcji kontrolki DataKeys . DataKeys Zwykle właściwość jest używana do pobierania DataKey obiektu dla określonego wiersza danych w kontrolceGridView. Jeśli jednak wystarczy pobrać DataKey obiekt aktualnie wybranego wiersza, możesz po prostu użyć SelectedDataKey właściwości jako skrótu.

Uwaga

Jest to takie samo, jak pobieranie DataKey obiektu w indeksie określonym przez SelectedIndex właściwość z kolekcji DataKeys . Możesz również użyć SelectedValue właściwości , aby pobrać wartość klucza danych dla aktualnie wybranego wiersza bezpośrednio.

Jeśli tworzysz ControlParameter obiekt i chcesz uzyskać dostęp do pola klucza innego niż pierwsze pole, użyj właściwości indeksowanej SelectedDataKey we PropertyName właściwości ControlParameter obiektu. Przykład przedstawiono poniżej.

Dotyczy

Zobacz też