ListItem Clase

Definición

Representa un elemento de datos en un control de lista enlazado a datos. Esta clase no puede heredarse.

public ref class ListItem sealed : System::Web::UI::IAttributeAccessor, System::Web::UI::IParserAccessor, System::Web::UI::IStateManager
[System.ComponentModel.TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
public sealed class ListItem : System.Web.UI.IAttributeAccessor, System.Web.UI.IParserAccessor, System.Web.UI.IStateManager
[<System.ComponentModel.TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))>]
type ListItem = class
    interface IStateManager
    interface IParserAccessor
    interface IAttributeAccessor
Public NotInheritable Class ListItem
Implements IAttributeAccessor, IParserAccessor, IStateManager
Herencia
ListItem
Atributos
Implementaciones

Ejemplos

En el ejemplo siguiente se muestra el uso de controles dentro de ListItem un ListBox control .

Nota

Los ejemplos de código siguientes usan el modelo de código de un solo archivo y es posible que no funcionen correctamente si se copian directamente en un archivo de código subyacente. Cada 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" %>
<!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>ListBox Example</title>
<script language="C#" runat="server">
 
         void SubmitBtn_Click(Object Sender, EventArgs e) {
             if (ListBox1.SelectedIndex > -1) {
                 Label1.Text="You chose: " + ListBox1.SelectedItem.Text;
                 Label1.Text+="<br /> with value: " + ListBox1.SelectedItem.Value;
             }
         }
 
     </script>
 
 </head>
 <body>
 
     <h3>ListBox Example</h3>
     <br />
 
     <form id="form1" runat="server">
 
         <asp:ListBox id="ListBox1" Width="100px" runat="server">
             <asp:ListItem>Item 1</asp:ListItem>
             <asp:ListItem>Item 2</asp:ListItem>
             <asp:ListItem>Item 3</asp:ListItem>
             <asp:ListItem Value="Value 4">Item 4</asp:ListItem>
             <asp:ListItem Text="Item 5" Value="Value 5" Selected="True"/>
             <asp:ListItem>Item 6</asp:ListItem>
         </asp:ListBox>
 
         <asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server" />
         
         <br />
         
         <asp:Label id="Label1" font-names="Verdana" font-size="10pt" runat="server"/>
         
     </form>
 
 </body>
 </html>
<%@ Page Language="VB" AutoEventWireup="True" %>
<!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>ListBox Example</title>
<script language="VB" runat="server">
 
         Sub SubmitBtn_Click(Sender As Object, e As EventArgs)
             If ListBox1.SelectedIndex > -1 Then
                 Label1.Text = "You chose: " & ListBox1.SelectedItem.Text
                 Label1.Text &= "<br /> with value: " & ListBox1.SelectedItem.Value
             End If
         End Sub
 
     </script>
 
 </head>
 <body>
 
     <h3>ListBox Example</h3>
     <br />
 
     <form id="form1" runat="server">
 
         <asp:ListBox id="ListBox1" Width="100px" runat="server">
             <asp:ListItem>Item 1</asp:ListItem>
             <asp:ListItem>Item 2</asp:ListItem>
             <asp:ListItem>Item 3</asp:ListItem>
             <asp:ListItem Value="Value 4">Item 4</asp:ListItem>
             <asp:ListItem Text="Item 5" Value="Value 5" Selected="True"/>
             <asp:ListItem>Item 6</asp:ListItem>
         </asp:ListBox>
 
         <asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server" />
         
         <br />
         
         <asp:Label id="Label1" font-names="Verdana" font-size="10pt" runat="server"/>
         
     </form>
 
 </body>
 </html>
<!-- This example demonstrates how to select multiple items from a DataList and add the 
selected items to a DataGrid. The example uses a foreach loop to iterate through 
the ListItem objects in the ListItemCollection of ListBox1. -->
<!-- This example demonstrates how to select multiple items from a DataList 
and add the selected items to a DataGrid. The example uses a For Each loop 
to iterate through the ListItem objects in the ListItemCollection of ListBox1. -->
<%@ 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">
<script language="C#" runat="server">
            // Global Variables.
            private DataView dv;
            private DataTable dt = new DataTable();

            private void Page_Load(object sender, System.EventArgs e)
            {
// <Snippet4>
                // Set the number of rows displayed in the ListBox to be
                // the number of items in the ListBoxCollection.
                ListBox1.Rows = ListBox1.Items.Count;
// </Snippet4>

                // If the DataTable is already stored in the Web form's default
                // HttpSessionState variable, then don't recreate the DataTable.
                if (Session["data"] == null)
                {
                    // Add columns to the DataTable.
                    dt.Columns.Add(new DataColumn("Item"));
                    dt.Columns.Add(new DataColumn("Price"));
            // Store the DataTable in the Session variable so it can 
                    // be accessed again later.
                    Session["data"] = dt;
                    
                    // Use the table to create a DataView, because the DataGrid
                    // can only bind to a data source that implements IEnumerable.
                    dv = new DataView(dt);
            
                    // Set the DataView as the data source, and bind it to the DataGrid.
                    DataGrid1.DataSource = dv;
                    DataGrid1.DataBind();
                }
            }

            private void addButton_Click(object sender, System.EventArgs e)
            {
// <Snippet5>
                // Add the items selected in ListBox1 to DataGrid1.
                foreach (ListItem item in ListBox1.Items)
                {
                    if (item.Selected)
                    {
                        // Add the item to the DataGrid.
                        // First, get the DataTable from the Session variable.
                        dt = (DataTable)Session["data"];
            
                        if (dt != null)
                        { 
                            // Create a new DataRow in the DataTable.
                            DataRow dr = dt.NewRow();
                            // Add the item to the new DataRow.
                            dr["Item"] = item.Text;
                            // Add the item's value to the DataRow.
                            dr["Price"] = item.Value;
                            // Add the DataRow to the DataTable.
                            dt.Rows.Add(dr);
// </Snippet5>

                            // Rebind the data to DataGrid1.
                            dv = new DataView(dt);
                            DataGrid1.DataSource = dv;
                            DataGrid1.DataBind();
                        }
                    }
                }
            }
        </script>
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
    <title> ListItemCollection Example </title>
</head>
    
    <body>
        <form id="form1" runat="server">

            <h3> ListItemCollection Example </h3>

            <table cellpadding="6" border="0">
                <tr>
                    <td valign="top">
                        <asp:ListBox id="ListBox1" runat="server" SelectionMode="Multiple">
                            <asp:ListItem Value=".89">apples</asp:ListItem>
                            <asp:ListItem Value=".49">bananas</asp:ListItem>
                            <asp:ListItem Value="2.99">cherries</asp:ListItem>
                            <asp:ListItem Value="1.49">grapes</asp:ListItem>
                            <asp:ListItem Value="2.00">mangos</asp:ListItem>
                            <asp:ListItem Value="1.09">oranges</asp:ListItem>
                        </asp:ListBox>
                    </td>

                    <td valign="top">
                        <asp:Button id="addButton" runat="server" Text="Add -->"
                            Width="100px" OnClick="addButton_Click"></asp:Button>
                    </td>

                    <td valign="top">
                        <asp:DataGrid Runat="server" ID="DataGrid1" CellPadding="4">
                        </asp:DataGrid>
                    </td>
                </tr>
            </table>        
        </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">
<script runat="server">
            ' Global Variables.
            Private dv As DataView
            Private dt As New DataTable()

            Private Sub Page_Load(sender As Object, e As System.EventArgs)
' <Snippet4>
                ' Set the number of rows displayed in the ListBox to be
                ' the number of items in the ListBoxCollection.
                ListBox1.Rows = ListBox1.Items.Count
' </Snippet4>

                ' If the DataTable is already stored in the Web form's default
                ' HttpSessionState variable, then don't recreate the DataTable.
                If Session("data") Is Nothing Then
                    ' Add columns to the DataTable.
                    dt.Columns.Add(New DataColumn("Item"))
                    dt.Columns.Add(New DataColumn("Price"))
            ' Store the DataTable in the Session variable so it can be 
                    ' accessed again later.
                    Session("data") = dt
                    
                    ' Use the table to create a DataView, because the DataGrid
                    ' can only bind to a data source that implements IEnumerable.
                    dv = New DataView(dt)
            
                    ' Set the DataView as the data source, and bind it to the DataGrid.
                    DataGrid1.DataSource = dv
                    DataGrid1.DataBind()
                End If
            End Sub

            Private Sub addButton_Click(sender As Object, e As System.EventArgs)
' <Snippet5>
                ' Add the items selected in ListBox1 to DataGrid1.
                Dim item As ListItem
                For Each item In ListBox1.Items
                    If item.Selected Then
                        ' Add the item to the DataGrid.
                        ' First, get the DataTable from the Session variable.
                        dt = CType(Session("data"), DataTable)
            
                        If  Not (dt Is Nothing) Then
                            ' Create a new DataRow in the DataTable.
                            Dim dr As DataRow
                            dr = dt.NewRow()
                            ' Add the item to the new DataRow.
                            dr("Item") = item.Text
                            ' Add the item's value to the DataRow.
                            dr("Price") = item.Value
                            ' Add the DataRow to the DataTable.
                            dt.Rows.Add(dr)
' </Snippet5>

                            ' Rebind the data to DataGrid1.
                            dv = new DataView(dt)
                            DataGrid1.DataSource = dv
                            DataGrid1.DataBind()
                        End If
                    End If
                Next item
            End Sub
        </script>
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
    <title> ListItemCollection Example </title>
</head>
    
    <body>
        <form id="form1" runat="server">

            <h3> ListItemCollection Example </h3>

            <table cellpadding="6" border="0">
                <tr>
                    <td valign="top">
                        <asp:ListBox id="ListBox1" runat="server" SelectionMode="Multiple">
                            <asp:ListItem Value=".89">apples</asp:ListItem>
                            <asp:ListItem Value=".49">bananas</asp:ListItem>
                            <asp:ListItem Value="2.99">cherries</asp:ListItem>
                            <asp:ListItem Value="1.49">grapes</asp:ListItem>
                            <asp:ListItem Value="2.00">mangos</asp:ListItem>
                            <asp:ListItem Value="1.09">oranges</asp:ListItem>
                        </asp:ListBox>
                    </td>

                    <td valign="top">
                        <asp:Button id="addButton" runat="server" Text="Add -->"
                            Width="100px" OnClick="addButton_Click"></asp:Button>
                    </td>

                    <td valign="top">
                        <asp:DataGrid Runat="server" ID="DataGrid1" CellPadding="4">
                        </asp:DataGrid>
                    </td>
                </tr>
            </table>        
        </form>
    </body>
</html>

Comentarios

Un ListItem control representa un elemento de datos individual dentro de un control de lista enlazado a datos, como un ListBox control o .RadioButtonList

Hay varias maneras de especificar el texto que se muestra para un elemento en el control de lista. El método más común es colocar texto en el contenido HTML interno. El contenido HTML interno es el texto entre las etiquetas de apertura y cierre del ListItem control. También puede usar la Text propiedad para especificar el texto que se muestra en el control de lista del elemento.

La Value propiedad permite asociar un valor al elemento del control de lista, además del texto que se muestra en el control. Por ejemplo, puede mostrar texto para un elemento en el control de lista, como "Item 1", y usar la Value propiedad para especificar un valor para ese elemento, como "$1.99".

Puede tener cualquier combinación del contenido HTML interno, Text, o Value propiedades establecidas. La salida HTML resultante para el ListItem control depende de la combinación de estas tres propiedades que se establecen. Por ejemplo, si las tres propiedades se establecen de la siguiente manera:

<asp:ListItem Value="Value 1" Text="Item 1">Inner 1</asp:ListItem>  

El contenido HTML interno se usa para el contenido HTML interno representado y la Value propiedad se usa para el Value atributo . La salida de representación HTML resultante es:

<option value="Value 1">Inner 1</option>  

En la tabla siguiente se muestra la combinación de propiedades de conjunto y la propiedad correspondiente usada para el contenido y Value el atributo HTML interno representados. Las tres columnas de la izquierda enumeran la combinación de propiedades de conjunto. Las dos columnas de la lista derecha que valor de propiedad se usa para el atributo correspondiente.

Contenido HTML interno Text (propiedad) Value (propiedad) Contenido HTML interno representado Atributo Value representado
Set Set Set Contenido HTML interno Value (propiedad)
Set Set Sin establecer Contenido HTML interno Contenido HTML interno
Set Sin establecer Set Contenido HTML interno Value (propiedad)
Set Sin establecer Sin establecer Contenido HTML interno Texto HTML interno
Sin establecer Set Set Text (propiedad) Value (propiedad)
Sin establecer Set Sin establecer Text (propiedad) Text (propiedad)
Sin establecer Sin establecer Set Value (propiedad) Value (propiedad)
Sin establecer Sin establecer Sin establecer Sin establecer Sin establecer

Nota

Dado que las Text propiedades y Value tienen un valor predeterminado de una cadena vacía, es posible tener elementos de lista vacíos en el control de lista.

Cuando se muestra un control de lista, cualquier ListItem control con su Selected propiedad establecida en true aparece resaltado en el control.

El ListItem control proporciona la Enabled propiedad para permitir especificar si un ListItem control está habilitado o deshabilitado. Un ListItem control deshabilitado está atenuado para indicar que no se puede seleccionar. Utilice esta propiedad para deshabilitar un ListItem control en un RadioButtonList control o en un CheckBoxList control .

Nota

No se puede usar esta propiedad para deshabilitar un ListItem control en un DropDownList control o ListBox control.

Para obtener una lista de valores de propiedad iniciales para una instancia de ListItem, vea el ListItem constructor .

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.

Constructores

ListItem()

Inicializa una nueva instancia de la clase ListItem.

ListItem(String)

Inicializa una nueva instancia de la clase ListItem con los datos de texto especificados.

ListItem(String, String)

Inicializa una nueva instancia de la clase ListItem con los datos de texto y valor especificados.

ListItem(String, String, Boolean)

Inicializa una nueva instancia de la clase ListItem con los datos de texto, valor y habilitación especificados.

Propiedades

Attributes

Obtiene una colección de pares de valores y nombres de atributo para ListItem que no son directamente compatibles con la clase.

Enabled

Obtiene o establece un valor que indica si el elemento de lista está habilitado.

Selected

Obtiene o establece un valor que indica si el elemento está seleccionado.

Text

Obtiene o establece el texto mostrado en el control de lista para el elemento representado por ListItem.

Value

Obtiene o establece el valor asociado a ListItem.

Métodos

Equals(Object)

Determina si el objeto especificado tiene el mismo valor y el mismo texto que el elemento de lista actual.

FromString(String)

Crea un elemento ListItem a partir del texto especificado.

GetHashCode()

Sirve como función hash para un tipo concreto y se puede usar en algoritmos hash y estructuras de datos, como las tablas hash.

GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

Implementaciones de interfaz explícitas

IAttributeAccessor.GetAttribute(String)

Devuelve el valor de atributo del control de elemento de lista que tiene el nombre de atributo especificado.

IAttributeAccessor.SetAttribute(String, String)

Establece un atributo del control de elemento de lista con el nombre y valor especificados.

IParserAccessor.AddParsedSubObject(Object)

Permite conservar la propiedad Text como contenido interno.

IStateManager.IsTrackingViewState

Para obtener una descripción de este miembro, vea IsTrackingViewState.

IStateManager.LoadViewState(Object)

Para obtener una descripción de este miembro, vea LoadViewState(Object).

IStateManager.SaveViewState()

Para obtener una descripción de este miembro, vea SaveViewState().

IStateManager.TrackViewState()

Para obtener una descripción de este miembro, vea TrackViewState().

Se aplica a

Consulte también