ListView.SelectedDataKey Propiedad

Definición

Obtiene el valor de la clave de datos para el elemento seleccionado en un control ListView.

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 de propiedad

DataKey

Clave de datos para el elemento seleccionado en un control ListView. El valor predeterminado es null, lo que indica que actualmente no hay ningún elemento seleccionado.

Atributos

Excepciones

No se ha especificado ninguna clave de datos en la propiedad DataKeyNames.

Ejemplos

En el ejemplo siguiente se muestra cómo usar el segundo campo de clave como parámetro en un escenario de maestro y detalle. Se usa un ListView control para mostrar los registros de la tabla Inventario de productos de la base de datos AdventureWorks. Cuando se selecciona un elemento en el ListView control, los detalles del producto se muestran en otro ListView control. ProductID es el segundo nombre de clave del primer ListView control. Para acceder a la segunda clave, el código usa el valor de ProductInventoryListView.SelectedDataKey[1] (ProductInventoryListView.SelectedDataKey(1) en Visual Basic) como para PropertyName el ControlParameter objeto . Este objeto de parámetro se usa a su vez por el SqlDataSource control al que está enlazado el segundo ListView control.

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

  protected void ProductInventoryListView_PagePropertiesChanging(object sender, 
    PagePropertiesChangingEventArgs e)
  {
    ProductInventoryListView.SelectedIndex = -1;
  }
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>ListView SelectedDataKey Example</title>
    <style type="text/css">
      .header
      {
        border: 1px solid #008080;
        background-color: #008080;
        color: White;
      }
      .item td { border: 1px solid #008080; }
    </style>
  </head>
  <body>
    <form id="form1" runat="server">
    
      <h3>ListView SelectedDataKey Example</h3>
      
      <asp:ListView runat="server" 
        ID="ProductInventoryListView"
        DataSourceID="ProductInventoryDataSource" 
        DataKeyNames="LocationID,ProductID" 
          OnPagePropertiesChanging="ProductInventoryListView_PagePropertiesChanging">
        <LayoutTemplate>
          <b>Product Inventory</b>
          <br />
          <table width="400px" runat="server" id="tblProducts">
            <tr class="header" runat="server">
              <th runat="server">&nbsp;</th>
              <th runat="server">Product ID</th>
              <th runat="server">Location ID</th>
              <th runat="server">Shelf</th>
              <th runat="server">Bin</th>
              <th runat="server">Quantity</th>
            </tr>
            <tr runat="server" id="itemPlaceholder" />
          </table>
          <asp:DataPager runat="server" ID="ProductInventoryPager">
            <Fields>
              <asp:NextPreviousPagerField ShowFirstPageButton="true"
                ShowLastPageButton="true" />
            </Fields>
          </asp:DataPager>
        </LayoutTemplate>
        <ItemTemplate>
          <tr class="item" runat="server">
            <td>
              <asp:ImageButton runat="server" 
                ID="SelectButton" 
                Width="15"
                Height="15"
                ImageUrl="~/images/select.jpg" 
                CommandName="Select" />
            </td>
            <td>
              <asp:Label runat="server" ID="ProductIDLabel" Text='<%#Eval("ProductID") %>' />
            </td>
            <td>
              <asp:Label runat="server" ID="LocationIDLabel" Text='<%#Eval("LocationID") %>' />
            </td>
            <td>
              <asp:Label runat="server" ID="ShelfLabel" Text='<%#Eval("Shelf") %>' />
            </td>
            <td>
              <asp:Label runat="server" ID="BinLabel" Text='<%#Eval("Bin") %>' />
            </td>
            <td>
              <asp:Label runat="server" ID="QuantityLabel" Text='<%#Eval("Quantity") %>' />
            </td>
          </tr>
        </ItemTemplate>
      </asp:ListView>
      <br /><br />
          
      <asp:ListView runat="server" ID="ProductListView"
        DataSourceID="ProductDataSource">
        <LayoutTemplate>
          <b>Product Details</b>          
          <table runat="server" id="tblDetails">
            <tr runat="server" id="itemPlaceholder" />
          </table>
        </LayoutTemplate>
        <ItemTemplate>
          <tr runat="server">
            <td class="header">Product ID:</td>
            <td>
              <asp:Label runat="server" ID="ProductLabel" Text='<%#Eval("ProductID") %>' />
            </td>
          </tr>
          <tr runat="server">
            <td class="header">Name:</td>
            <td>
              <asp:Label runat="server" ID="NameLabel" Text='<%#Eval("Name") %>' />
            </td>
          </tr>
          <tr runat="server">
            <td class="header">Color:</td>
            <td>
              <asp:Label runat="server" ID="ColorLabel" Text='<%#Eval("Color") %>' />
            </td>
          </tr>
          <tr runat="server">
            <td class="header">Price:</td>
            <td>
              <asp:Label runat="server" ID="ListPriceLabel" Text='<%#Eval("ListPrice", "{0:c}") %>' />
            </td>
          </tr>
        </ItemTemplate>
      </asp:ListView>
       
      <!-- This example uses Microsoft SQL Server and connects      -->
      <!-- to the AdventureWorks sample database. Use an ASP.NET    -->
      <!-- expression to retrieve the connection string value       -->
      <!-- from the Web.config file.                                -->
      <asp:SqlDataSource ID="ProductInventoryDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [ProductID], [LocationID], [Shelf], [Bin], [Quantity]
                       FROM Production.ProductInventory">
      </asp:SqlDataSource>
      
      <asp:SqlDataSource ID="ProductDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [ProductID], [Name], [Color], [ListPrice], [ProductNumber]
                         FROM Production.Product
                         WHERE ProductID = @ProductID
                         ORDER BY [Name]">
          <SelectParameters>
            <asp:ControlParameter Name="ProductID" 
              DefaultValue="0"
              ControlID="ProductInventoryListView" 
              PropertyName="SelectedDataKey[1]"  />
          </SelectParameters>
      </asp:SqlDataSource>
       
    </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">

  Protected Sub ProductInventoryListView_PagePropertiesChanging(ByVal sender As Object, _
    ByVal e As PagePropertiesChangingEventArgs)
    
    ProductInventoryListView.SelectedIndex = -1
    
  End Sub
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>ListView SelectedDataKey Example</title>
    <style type="text/css">
      .header
      {
        border: 1px solid #008080;
        background-color: #008080;
        color: White;
      }
      .item td { border: 1px solid #008080; }
    </style>
  </head>
  <body>
    <form id="form1" runat="server">
    
      <h3>ListView SelectedDataKey Example</h3>
      
      <asp:ListView runat="server" 
        ID="ProductInventoryListView"
        DataSourceID="ProductInventoryDataSource" 
        DataKeyNames="LocationID,ProductID" 
          OnPagePropertiesChanging="ProductInventoryListView_PagePropertiesChanging">
        <LayoutTemplate>
          <b>Product Inventory</b>
          <br />
          <table width="400px" runat="server" id="tblProducts">
            <tr class="header" runat="server">
              <th runat="server">&nbsp;</th>
              <th runat="server">Product ID</th>
              <th runat="server">Location ID</th>
              <th runat="server">Shelf</th>
              <th runat="server">Bin</th>
              <th runat="server">Quantity</th>
            </tr>
            <tr runat="server" id="itemPlaceholder" />
          </table>
          <asp:DataPager runat="server" ID="ProductInventoryPager">
            <Fields>
              <asp:NextPreviousPagerField ShowFirstPageButton="true"
                ShowLastPageButton="true" />
            </Fields>
          </asp:DataPager>
        </LayoutTemplate>
        <ItemTemplate>
          <tr class="item" runat="server">
            <td>
              <asp:ImageButton runat="server" 
                ID="SelectButton" 
                Width="15"
                Height="15"
                ImageUrl="~/images/select.jpg" 
                CommandName="Select" />
            </td>
            <td>
              <asp:Label runat="server" ID="ProductIDLabel" Text='<%#Eval("ProductID") %>' />
            </td>
            <td>
              <asp:Label runat="server" ID="LocationIDLabel" Text='<%#Eval("LocationID") %>' />
            </td>
            <td>
              <asp:Label runat="server" ID="ShelfLabel" Text='<%#Eval("Shelf") %>' />
            </td>
            <td>
              <asp:Label runat="server" ID="BinLabel" Text='<%#Eval("Bin") %>' />
            </td>
            <td>
              <asp:Label runat="server" ID="QuantityLabel" Text='<%#Eval("Quantity") %>' />
            </td>
          </tr>
        </ItemTemplate>
      </asp:ListView>
      <br /><br />
          
      <asp:ListView runat="server" ID="ProductListView"
        DataSourceID="ProductDataSource">
        <LayoutTemplate>
          <b>Product Details</b>          
          <table runat="server" id="tblDetails">
            <tr runat="server" id="itemPlaceholder" />
          </table>
        </LayoutTemplate>
        <ItemTemplate>
          <tr runat="server">
            <td class="header">Product ID:</td>
            <td>
              <asp:Label runat="server" ID="ProductLabel" Text='<%#Eval("ProductID") %>' />
            </td>
          </tr>
          <tr runat="server">
            <td class="header">Name:</td>
            <td>
              <asp:Label runat="server" ID="NameLabel" Text='<%#Eval("Name") %>' />
            </td>
          </tr>
          <tr runat="server">
            <td class="header">Color:</td>
            <td>
              <asp:Label runat="server" ID="ColorLabel" Text='<%#Eval("Color") %>' />
            </td>
          </tr>
          <tr runat="server">
            <td class="header">Price:</td>
            <td>
              <asp:Label runat="server" ID="ListPriceLabel" Text='<%#Eval("ListPrice", "{0:c}") %>' />
            </td>
          </tr>
        </ItemTemplate>
      </asp:ListView>
       
      <!-- This example uses Microsoft SQL Server and connects      -->
      <!-- to the AdventureWorks sample database. Use an ASP.NET    -->
      <!-- expression to retrieve the connection string value       -->
      <!-- from the Web.config file.                                -->
      <asp:SqlDataSource ID="ProductInventoryDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [ProductID], [LocationID], [Shelf], [Bin], [Quantity]
                       FROM Production.ProductInventory">
      </asp:SqlDataSource>
      
      <asp:SqlDataSource ID="ProductDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        SelectCommand="SELECT [ProductID], [Name], [Color], [ListPrice], [ProductNumber]
                         FROM Production.Product
                         WHERE ProductID = @ProductID
                         ORDER BY [Name]">
          <SelectParameters>
            <asp:ControlParameter Name="ProductID" 
              DefaultValue="0"
              ControlID="ProductInventoryListView" 
              PropertyName="SelectedDataKey[1]"  />
          </SelectParameters>
      </asp:SqlDataSource>
       
    </form>
  </body>
</html>

Comentarios

Cuando se establece la DataKeyNames propiedad , el ListView control crea un DataKey objeto para cada elemento del control utilizando el valor o los valores del campo o campos especificados. A DataKey continuación, los objetos se agregan a la colección del DataKeys control. Normalmente, la DataKeys propiedad se usa para recuperar el DataKey objeto de un elemento de datos específico en el ListView control . Sin embargo, si desea recuperar solo el DataKey objeto del elemento seleccionado actualmente, puede usar la SelectedDataKey propiedad como acceso directo.

El uso de la SelectedDataKey propiedad es el mismo que recuperar el DataKey objeto de la DataKeys colección en el índice especificado por la SelectedIndex propiedad . También puede usar la SelectedValue propiedad para recuperar el valor de clave de datos del elemento seleccionado actualmente directamente.

Si va a crear un ControlParameter objeto y desea tener acceso a un campo de clave distinto del primer campo, utilice la propiedad indizada SelectedDataKey en la PropertyName propiedad del ControlParameter objeto .

Se aplica a

Consulte también