GridView.SelectedDataKey Propriedade

Definição

Obtém o objeto de DataKey que contém o valor de chave de dados para a linha selecionada em um controle do GridView.

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

Valor da propriedade

DataKey

O DataKey para a linha selecionada em um controle do GridView. O padrão é null, que indica que nenhuma linha está selecionada no momento.

Atributos

Exceções

Nenhuma chave de dados está especificada na propriedade DataKeyNames.

Exemplos

O exemplo a seguir demonstra como usar a SelectedDataKey propriedade para determinar o valor da chave de dados da linha selecionada em um GridView controle.


<%@ 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>

O exemplo a seguir demonstra como usar o segundo campo de chave como um parâmetro em um cenário mestre/detalhe. Um GridView controle é usado para exibir registros da tabela Detalhes da Ordem do banco de dados Northwind. Quando um registro é selecionado no GridView controle, os detalhes do produto da tabela Produtos são exibidos em um DetailsView controle. ProductID é o segundo nome de chave no GridView controle. Para acessar a segunda chave, o valor de GridView1.SelectedDataKey[1] é usado como o PropertyName ControlParameter objeto do SqlDataSource controle do DetailsView controle.


<%@ 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>

Comentários

Quando a DataKeyNames propriedade é definida, o GridView controle cria automaticamente um DataKey objeto para cada linha no controle usando o valor ou os valores do campo ou campos especificados. Em DataKey seguida, os objetos são adicionados à coleção do DataKeys controle. Normalmente, a DataKeys propriedade é usada para recuperar o DataKey objeto para uma linha de dados específica no GridView controle. No entanto, se você precisar apenas recuperar o DataKey objeto da linha selecionada no momento, poderá simplesmente usar a SelectedDataKey propriedade como um atalho.

Observação

Isso é o mesmo que recuperar o DataKey objeto no índice especificado pela SelectedIndex propriedade da DataKeys coleção. Você também pode usar a SelectedValue propriedade para recuperar o valor da chave de dados para a linha selecionada no momento diretamente.

Se você estiver criando um ControlParameter objeto e quiser acessar um campo de chave diferente do primeiro campo, use a propriedade indexada SelectedDataKey na PropertyName propriedade do ControlParameter objeto. Um exemplo é mostrado abaixo.

Aplica-se a

Confira também