DataList.SelectedItemTemplate Propiedad

Definición

Obtiene o establece la plantilla para el elemento seleccionado del control DataList.

public:
 virtual property System::Web::UI::ITemplate ^ SelectedItemTemplate { System::Web::UI::ITemplate ^ get(); void set(System::Web::UI::ITemplate ^ value); };
[System.ComponentModel.Browsable(false)]
[System.Web.UI.PersistenceMode(System.Web.UI.PersistenceMode.InnerProperty)]
[System.Web.UI.TemplateContainer(typeof(System.Web.UI.WebControls.DataListItem))]
public virtual System.Web.UI.ITemplate SelectedItemTemplate { get; set; }
[<System.ComponentModel.Browsable(false)>]
[<System.Web.UI.PersistenceMode(System.Web.UI.PersistenceMode.InnerProperty)>]
[<System.Web.UI.TemplateContainer(typeof(System.Web.UI.WebControls.DataListItem))>]
member this.SelectedItemTemplate : System.Web.UI.ITemplate with get, set
Public Overridable Property SelectedItemTemplate As ITemplate

Valor de propiedad

Objeto ITemplate que contiene la plantilla para el elemento seleccionado del control DataList. El valor predeterminado es null.

Atributos

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar la SelectedItemTemplate propiedad para controlar el contenido del elemento seleccionado en el DataList control .

Nota

En el ejemplo de código siguiente se usa el modelo de código de un solo archivo y es posible que no funcione correctamente si se copia directamente en un archivo de código subyacente. Este ejemplo de código debe copiarse en un archivo de texto vacío que tenga una extensión .aspx. Para obtener más información sobre el modelo de código de Web Forms, consulte ASP.NET Web Forms Modelo de código de página.


<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!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>
    <title>DataList Select Example</title>
<script runat="server">

      ICollection CreateDataSource() 
      {
      
         // Create sample data for the DataList control.
         DataTable dt = new DataTable();
         DataRow dr;
 
         // Define the columns of the table.
         dt.Columns.Add(new DataColumn("Item", typeof(Int32)));
         dt.Columns.Add(new DataColumn("Qty", typeof(Int32)));
         dt.Columns.Add(new DataColumn("Price", typeof(double)));
 
         // Populate the table with sample values.
         for (int i = 0; i < 9; i++) 
         {
            dr = dt.NewRow();
 
            dr[0] = i;
            dr[1] = i * 2;
            dr[2] = 1.23 * (i + 1);
 
            dt.Rows.Add(dr);
         }
 
         DataView dv = new DataView(dt);
         return dv;

      }
 
      void Page_Load(Object sender, EventArgs e) 
      {

         // Load sample data only once, when the page is first loaded.
         if (!IsPostBack) 
         {
            ItemsList.DataSource = CreateDataSource();
            ItemsList.DataBind();
         }

      }

      void Item_Command(Object sender, DataListCommandEventArgs e) 
      {
        
         // Set the SelectedIndex property to select an item in the DataList.
         ItemsList.SelectedIndex = e.Item.ItemIndex;

         // Rebind the data source to the DataList to refresh the control.
         ItemsList.DataSource = CreateDataSource();
         ItemsList.DataBind();

      }

   </script>

</head>
<body>

   <form id="form1" runat="server">

      <h3>DataList Select Example</h3>

      Click <b>Select</b> to select an item.

      <br /><br />
       
      <asp:DataList id="ItemsList"
           GridLines="Both"
           CellPadding="3"
           CellSpacing="0"           
           OnItemCommand="Item_Command"
           runat="server">

         <HeaderStyle BackColor="#aaaadd">
         </HeaderStyle>

         <AlternatingItemStyle BackColor="Gainsboro">
         </AlternatingItemStyle>

         <SelectedItemStyle BackColor="Yellow">
         </SelectedItemStyle>

         <HeaderTemplate>

            Items

         </HeaderTemplate>
         
         <ItemTemplate>

            <asp:LinkButton id="SelectButton" 
                 Text="Select" 
                 CommandName="Select"
                 runat="server"/>

            Item <%# DataBinder.Eval(Container.DataItem, "Item") %>

         </ItemTemplate>
              
         <SelectedItemTemplate>

            Item:
            <asp:Label id="ItemLabel" 
                 Text='<%# DataBinder.Eval(Container.DataItem, "Item") %>' 
                 runat="server"/>

            <br />

            Quantity:
            <asp:Label id="QtyLabel" 
                 Text='<%# DataBinder.Eval(Container.DataItem, "Qty") %>' 
                 runat="server"/>

            <br />

            Price:
            <asp:Label id="PriceLabel" 
                 Text='<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}") %>' 
                 runat="server"/>

         </SelectedItemTemplate>

      </asp:DataList>

   </form>

</body>
</html>

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!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>
    <title>DataList Select Example</title>
<script runat="server">

      Function CreateDataSource() As ICollection 
      
         ' Create sample data for the DataList control.
         Dim dt As DataTable = New DataTable()
         Dim dr As DataRow
 
         ' Define the columns of the table.
         dt.Columns.Add(New DataColumn("Item", GetType(Int32)))
         dt.Columns.Add(New DataColumn("Qty", GetType(Int32)))
         dt.Columns.Add(New DataColumn("Price", GetType(Double)))
 
         ' Populate the table with sample values.
         Dim i As Integer

         For i = 0 To 8 

            dr = dt.NewRow()
 
            dr(0) = i
            dr(1) = i * 2
            dr(2) = 1.23 * (i + 1)
 
            dt.Rows.Add(dr)
         
         Next i
 
         Dim dv As DataView = New DataView(dt)
         Return dv
      
      End Function
 
      Sub Page_Load(sender As Object, e As EventArgs) 

         ' Load sample data only once, when the page is first loaded.
         If Not IsPostBack Then 
         
            ItemsList.DataSource = CreateDataSource()
            ItemsList.DataBind()
         
         End If

      End Sub

      Sub Item_Command(sender As Object, e As DataListCommandEventArgs) 
        
         ' Set the SelectedIndex property to select an item in the DataList.
         ItemsList.SelectedIndex = e.Item.ItemIndex

         ' Rebind the data source to the DataList to refresh the control.
         ItemsList.DataSource = CreateDataSource()
         ItemsList.DataBind()

      End Sub

   </script>

</head>
<body>

   <form id="form1" runat="server">

      <h3>DataList Select Example</h3>

      Click <b>Select</b> to select an item.

      <br /><br />
       
      <asp:DataList id="ItemsList"
           GridLines="Both"
           CellPadding="3"
           CellSpacing="0"           
           OnItemCommand="Item_Command"
           runat="server">

         <HeaderStyle BackColor="#aaaadd">
         </HeaderStyle>

         <AlternatingItemStyle BackColor="Gainsboro">
         </AlternatingItemStyle>

         <SelectedItemStyle BackColor="Yellow">
         </SelectedItemStyle>

         <HeaderTemplate>

            Items

         </HeaderTemplate>
         
         <ItemTemplate>

            <asp:LinkButton id="SelectButton" 
                 Text="Select" 
                 CommandName="Select"
                 runat="server"/>

            Item <%# DataBinder.Eval(Container.DataItem, "Item") %>

         </ItemTemplate>
              
         <SelectedItemTemplate>

            Item:
            <asp:Label id="ItemLabel" 
                 Text='<%# DataBinder.Eval(Container.DataItem, "Item") %>' 
                 runat="server"/>

            <br />

            Quantity:
            <asp:Label id="QtyLabel" 
                 Text='<%# DataBinder.Eval(Container.DataItem, "Qty") %>' 
                 runat="server"/>

            <br />

            Price:
            <asp:Label id="PriceLabel" 
                 Text='<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}") %>' 
                 runat="server"/>

         </SelectedItemTemplate>

      </asp:DataList>

   </form>

</body>
</html>

Comentarios

Utilice la SelectedItemTemplate propiedad para controlar el contenido del elemento seleccionado. La apariencia del elemento seleccionado se controla mediante la SelectedItemStyle propiedad .

Para especificar una plantilla para el elemento seleccionado, coloque las <SelectedItemTemplate> etiquetas entre las etiquetas de apertura y cierre del DataList control. A continuación, puede enumerar el contenido de la plantilla entre las etiquetas de apertura y cierre <SelectedItemTemplate> .

Precaución

Este control se puede usar para mostrar la entrada del usuario, que puede incluir un script de cliente malintencionado. Compruebe cualquier información que se envíe desde un cliente para el script ejecutable, las instrucciones SQL u otro código antes de mostrarla en la aplicación. Puede usar controles de validación para comprobar la entrada del usuario antes de mostrar el texto de entrada en un control. ASP.NET proporciona una característica de validación de solicitudes de entrada para bloquear script y HTML en la entrada del usuario. Para obtener más información, vea Protección de controles estándar, Protección contra vulnerabilidades de seguridad de script en una aplicación web mediante la aplicación de codificación HTML en cadenas y validación de la entrada de usuario en ASP.NET Web Pages.

Se aplica a

Consulte también