Suggérer une traduction
 
Suggestions d'autres utilisateurs :

progress indicator
Aucune autre suggestion.
Cliquez pour évaluer et commenter
MSDN
MSDN Library
Développement .NET
.NET Framework 4
Espaces de noms System.Web
System.Web.UI.WebControls
ListItem, classe
Réduire tout/Développer tout Réduire tout
Affichage du contenu :  côte à côteAffichage du contenu : côte à côte
.NET Framework Class Library
ListItem Class

Represents a data item in a data-bound list control. This class cannot be inherited.

System..::.Object
  System.Web.UI.WebControls..::.ListItem

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web (in System.Web.dll)
Visual Basic
<TypeConverterAttribute(GetType(ExpandableObjectConverter))> _
Public NotInheritable Class ListItem _
    Implements IStateManager, IParserAccessor, IAttributeAccessor
C#
[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public sealed class ListItem : IStateManager, 
    IParserAccessor, IAttributeAccessor
Visual C++
[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public ref class ListItem sealed : IStateManager, 
    IParserAccessor, IAttributeAccessor
F#
[<Sealed>]
[<TypeConverterAttribute(typeof(ExpandableObjectConverter))>]
type ListItem =  
    class
        interface IStateManager
        interface IParserAccessor
        interface IAttributeAccessor
    end

The ListItem type exposes the following members.

  NameDescription
Public methodListItem()()()Initializes a new instance of the ListItem class.
Public methodListItem(String)Initializes a new instance of the ListItem class with the specified text data.
Public methodListItem(String, String)Initializes a new instance of the ListItem class with the specified text and value data.
Public methodListItem(String, String, Boolean)Initializes a new instance of the ListItem class with the specified text, value, and enabled data.
Top
  NameDescription
Public propertyAttributesGets a collection of attribute name and value pairs for the ListItem that are not directly supported by the class.
Public propertyEnabledGets or sets a value indicating whether the list item is enabled.
Public propertySelectedGets or sets a value indicating whether the item is selected.
Public propertyTextGets or sets the text displayed in a list control for the item represented by the ListItem.
Public propertyValueGets or sets the value associated with the ListItem.
Top
  NameDescription
Public methodEqualsDetermines whether the specified object has the same value and text as the current list item. (Overrides Object..::.Equals(Object).)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodStatic memberFromStringCreates a ListItem from the specified text.
Public methodGetHashCodeServes as a hash function for a particular type, and is suitable for use in hashing algorithms and data structures like a hash table. (Overrides Object..::.GetHashCode()()().)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Overrides Object..::.ToString()()().)
Top
  NameDescription
Explicit interface implemetationPrivate methodIAttributeAccessor..::.GetAttributeInfrastructure. Returns the attribute value of the list item control having the specified attribute name.
Explicit interface implemetationPrivate methodIAttributeAccessor..::.SetAttributeInfrastructure. Sets an attribute of the list item control with the specified name and value.
Explicit interface implemetationPrivate methodIParserAccessor..::.AddParsedSubObjectInfrastructure. Allows the Text property to be persisted as inner content.
Explicit interface implemetationPrivate propertyIStateManager..::.IsTrackingViewStateInfrastructure. For a description of this member, see IStateManager..::.IsTrackingViewState.
Explicit interface implemetationPrivate methodIStateManager..::.LoadViewStateInfrastructure. For a description of this member, see IStateManager..::.LoadViewState.
Explicit interface implemetationPrivate methodIStateManager..::.SaveViewStateInfrastructure. For a description of this member, see IStateManager..::.SaveViewState.
Explicit interface implemetationPrivate methodIStateManager..::.TrackViewStateInfrastructure. For a description of this member, see IStateManager..::.TrackViewState.
Top

A ListItem control represents an individual data item within a data-bound list control, such as a ListBox or a RadioButtonList control.

There are several ways to specify the text displayed for an item in the list control. The most common method is by placing text in the inner HTML content. The inner HTML content is the text between the opening and closing tags of the ListItem control. You can also use the Text property to specify the text displayed in the list control for the item.

The Value property allows you to associate a value with the item in the list control, in addition to the text displayed in the control. For example, you can display text for an item in the list control, such as "Item 1", and use the Value property to specify a value for that item, such as "$1.99".

You can have any combination of the inner HTML content, Text, or Value properties set. The resulting HTML output for the ListItem control depends on the combination of these three properties that are set. For example, if all three properties are set as follows:

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

The inner HTML content is used for rendered inner HTML content and the Value property is used for the Value attribute. The resulting HTML rendering output is:

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

The following table lists the combination of set properties and the corresponding property used for the rendered inner HTML content and Value attribute. The three columns on the left list the combination of set properties. The two columns on the right list which property value is used for the corresponding attribute.

Inner HTML content

Text property

Value property

Rendered Inner HTML content

Rendered Value attribute

Set

Set

Set

Inner HTML content

Value property

Set

Set

Not set

Inner HTML content

Inner HTML content

Set

Not set

Set

Inner HTML content

Value property

Set

Not set

Not set

Inner HTML content

Inner HTML text

Not set

Set

Set

Text property

Value property

Not set

Set

Not set

Text property

Text property

Not set

Not set

Set

Value property

Value property

Not set

Not set

Not set

Not set

Not set

NoteNote

Because the Text and Value properties each have a default value of an empty string, it is possible to have empty list items in the list control.

When a list control is displayed, any ListItem control with its Selected property set to true appears highlighted in the control.

The ListItem control provides the Enabled property to allow you to specify whether a ListItem control is enabled or disabled. A ListItem control that is disabled is dimmed to indicate that it cannot be selected. Use this property to disable a ListItem control in either a RadioButtonList control or a CheckBoxList control.

NoteNote

You cannot use this property to disable a ListItem control in a DropDownList control or ListBox control.

For a list of initial property values for an instance of ListItem, see the ListItem constructor.

Caution noteCaution

This control can be used to display user input, which might include malicious client script. Check any information that is sent from a client for executable script, SQL statements, or other code before displaying it in your application. You can use validation controls to verify user input before displaying the input text in a control. ASP.NET provides an input request validation feature to block script and HTML in user input. For more information, see Securing Standard ControlsHow to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings, and Validating User Input in ASP.NET Web Pages.

The following example illustrates the use of ListItem controls within a ListBox control.

NoteNote

The following code samples use the single-file code model and may not work correctly if copied directly into a code-behind file. Each code sample must be copied into an empty text file that has an .aspx extension. For more information on the Web Forms code model, see ASP.NET Web Page Code Model.

Visual Basic
<%@ 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  >
 <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>
          
C#
<%@ 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  >
 <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>
          
Visual Basic
<!-- 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="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)
                ' Set the number of rows displayed in the ListBox to be
                ' the number of items in the ListBoxCollection.
                ListBox1.Rows = ListBox1.Items.Count

                ' 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)
                ' 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)

                            ' Rebind the data to DataGrid1.
                            dv = new DataView(dt)
                            DataGrid1.DataSource = dv
                            DataGrid1.DataBind()
                        End If
                    End If
                Next item
            End Sub
        </script>
<html  >
    <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>
C#
<!-- 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. -->



...


<%@ 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)
            {
                // Set the number of rows displayed in the ListBox to be
                // the number of items in the ListBoxCollection.
                ListBox1.Rows = ListBox1.Items.Count;

                // 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)
            {
                // 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);

                            // Rebind the data to DataGrid1.
                            dv = new DataView(dt);
                            DataGrid1.DataSource = dv;
                            DataGrid1.DataBind();
                        }
                    }
                }
            }
        </script>
<html  >
    <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>

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Bibliothèque de classes .NET Framework
ListItem, classe

Représente un élément de données dans un contrôle de liste lié aux données. Cette classe ne peut pas être héritée.

System..::.Object
  System.Web.UI.WebControls..::.ListItem

Espace de noms :  System.Web.UI.WebControls
Assembly :  System.Web (dans System.Web.dll)
Visual Basic
<TypeConverterAttribute(GetType(ExpandableObjectConverter))> _
Public NotInheritable Class ListItem _
    Implements IStateManager, IParserAccessor, IAttributeAccessor
C#
[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public sealed class ListItem : IStateManager, 
    IParserAccessor, IAttributeAccessor
VisualC++
[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public ref class ListItem sealed : IStateManager, 
    IParserAccessor, IAttributeAccessor
F#
[<Sealed>]
[<TypeConverterAttribute(typeof(ExpandableObjectConverter))>]
type ListItem =  
    class
        interface IStateManager
        interface IParserAccessor
        interface IAttributeAccessor
    end

Le type ListItem expose les membres suivants.

  NomDescription
Méthode publiqueListItem()()()Initialise une nouvelle instance de la classe ListItem.
Méthode publiqueListItem(String)Initialise une nouvelle instance de la classe ListItem avec le texte spécifié.
Méthode publiqueListItem(String, String)Initialise une nouvelle instance de la classe ListItem avec le texte et la valeur spécifiés.
Méthode publiqueListItem(String, String, Boolean)Initialise une nouvelle instance de la classe ListItem avec le texte, la valeur et les données activées spécifiés.
Début
  NomDescription
Propriété publiqueAttributesObtient une collection de paires nom-valeur pour les ListItem non directement prises en charge par la classe.
Propriété publiqueEnabledObtient ou définit une valeur indiquant si l'élément de liste est activé.
Propriété publiqueSelectedObtient ou définit une valeur indiquant si l'élément est sélectionné.
Propriété publiqueTextObtient ou définit le texte à afficher dans un contrôle de liste pour l'élément représenté par ListItem.
Propriété publiqueValueObtient ou définit la valeur associée à ListItem.
Début
  NomDescription
Méthode publiqueEqualsDétermine si l'objet spécifié a la même valeur et le même texte que l'élément de liste actuel. (Substitue Object..::.Equals(Object).)
Méthode protégéeFinalizeAutorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de netto***ge avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.)
Méthode publiqueMembre statiqueFromStringCrée ListItem à partir du texte spécifié.
Méthode publiqueGetHashCodeSert de fonction de hachage pour un type particulier et est approprié à une utilisation dans des algorithmes de hachage et des structures de données telles qu'une table de hachage. (Substitue Object..::.GetHashCode()()().)
Méthode publiqueGetTypeObtient le Type de l'instance actuelle. (Hérité de Object.)
Méthode protégéeMemberwiseCloneCrée une copie superficielle de l'objet Object actif. (Hérité de Object.)
Méthode publiqueToStringRetourne une chaîne qui représente l'objet actuel. (Substitue Object..::.ToString()()().)
Début
  NomDescription
Implémentation d'interface expliciteMéthode privéeIAttributeAccessor..::.GetAttributeInfrastructure. Retourne la valeur d'attribut du contrôle d'élément de liste ayant le nom d'attribut spécifié.
Implémentation d'interface expliciteMéthode privéeIAttributeAccessor..::.SetAttributeInfrastructure. Définit un attribut du contrôle d'élément de liste avec le nom et la valeur spécifiés.
Implémentation d'interface expliciteMéthode privéeIParserAccessor..::.AddParsedSubObjectInfrastructure. Permet à la propriété Text d'être persistante comme contenu interne.
Implémentation d'interface explicitePropriété privéeIStateManager..::.IsTrackingViewStateInfrastructure. Pour obtenir une description de ce membre, consultez IStateManager..::.IsTrackingViewState.
Implémentation d'interface expliciteMéthode privéeIStateManager..::.LoadViewStateInfrastructure. Pour une description de ce membre, consultez IStateManager..::.LoadViewState.
Implémentation d'interface expliciteMéthode privéeIStateManager..::.SaveViewStateInfrastructure. Pour une description de ce membre, consultez IStateManager..::.SaveViewState.
Implémentation d'interface expliciteMéthode privéeIStateManager..::.TrackViewStateInfrastructure. Pour obtenir une description de ce membre, consultez IStateManager..::.TrackViewState.
Début

Un contrôle ListItem représente un élément de données individuel dans un contrôle de liste lié aux données, tel qu'un contrôle ListBox ou RadioButtonList.

Il y a plusieurs façons de spécifier quel texte sera affiché pour un élément du contrôle de liste. La méthode la plus courante consiste à placer le texte dans le contenu HTML interne. Le contenu HTML interne est le texte situé entre les balises d'ouverture et de fermeture du contrôle ListItem. Vous pouvez également utiliser la propriété Text pour spécifier le texte à afficher dans le contrôle de liste de l'élément.

La propriété Value permet d'associer une valeur à un élément du contrôle de liste, outre le texte affiché dans le contrôle. Par exemple, vous pouvez afficher le texte d'un élément du contrôle de liste, tel que "Item 1" puis, avec la propriété Value, spécifier la valeur de cet élément, par exemple "$1.99".

La propriété Text ou Value étant définie, toute combinaison du contenu HTML interne est possible. La sortie HTML qui résulte du contrôle ListItem dépend de la combinaison de ces trois propriétés définies. Par exemple, si les trois propriétés sont définies de la manière suivante :

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

Le contenu HTML interne est utilisé pour le contenu HTML interne rendu et la propriété Value est utilisée pour l'attribut Value. Voici la sortie de rendu HTML :

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

Le tableau suivant répertorie la combinaison des propriétés définies et de la propriété correspondante, utilisée pour le contenu HTML interne et l'attribut Value. Les trois colonnes de gauche énumèrent les combinaisons de propriétés définies. Les deux colonnes de droite indiquent la valeur utilisée par la propriété pour l'attribut correspondant.

Contenu HTML interne

Text, propriété

Value, propriété

Contenu HTML interne rendu

Attribut Value rendu

Set

Set

Set

Contenu HTML interne

Value, propriété

Set

Set

Non définie

Contenu HTML interne

Contenu HTML interne

Set

Non définie

Set

Contenu HTML interne

Value, propriété

Set

Non définie

Non définie

Contenu HTML interne

Texte HTML interne

Non définie

Set

Set

Text, propriété

Value, propriété

Non définie

Set

Non définie

Text, propriété

Text, propriété

Non définie

Non définie

Set

Value, propriété

Value, propriété

Non définie

Non définie

Non définie

Non définie

Non définie

RemarqueRemarque

Étant donné que les propriétés Text et Value ont une chaîne vide comme valeur par défaut, il est possible d'avoir des éléments de liste vides dans le contrôle de liste.

Lorsqu'un contrôle de liste est affiché, tout contrôle ListItem dont la propriété Selected a la valeur true apparaît en surbrillance dans le contrôle.

Le contrôle ListItem fournit la propriété Enabled pour vous permettre de spécifier si un contrôle ListItem est activé ou désactivé. Un contrôle ListItem qui est désactivé est estompé pour indiquer qu'il ne peut pas être sélectionné. Utilisez cette propriété pour désactiver un contrôle ListItem dans un contrôle RadioButtonList ou dans un contrôle CheckBoxList.

RemarqueRemarque

Vous ne pouvez pas utiliser cette propriété pour désactiver un contrôle ListItem dans un contrôle DropDownList ou dans un contrôle ListBox.

Pour obtenir la liste des valeurs de propriétés initiales d'une instance de ListItem, consultez le constructeur ListItem.

Remarque AttentionAttention

Ce contrôle peut être utilisé pour afficher des entrées d'utilisateur qui peuvent inclure un script client nuisible. Vérifiez toutes les informations envoyées par un client pour un script exécutable, des instructions SQL ou un autre code avant de les afficher dans votre application. Vous pouvez utiliser des contrôles de validation pour vérifier les entrées d'utilisateur avant d'afficher le texte d'entrée dans un contrôle. ASP.NET fournit une fonctionnalité de validation de la demande d'entrée pour bloquer les scripts et le code HTML dans les entrées d'utilisateur. Pour plus d'informations, consultez Sécurisation de contrôles standard, Comment : se protéger contre les attaques de script dans une application Web en utilisant l'encodage HTML et Validation des entrées d'utilisateur dans des pages Web ASP.NET.

L'exemple suivant illustre l'utilisation de contrôles ListItem dans un contrôle ListBox.

RemarqueRemarque

Les exemples de code suivants utilisent un modèle de code de fichier unique ; il est possible qu'ils ne fonctionnent pas correctement s'ils sont directement copiés dans un fichier code-behind. Chaque exemple de code doit être copié dans un fichier texte vide doté d'une extension .aspx. Pour plus d'informations sur le modèle de code des Web Forms, consultez Modèle de code des pages Web ASP.NET.

Visual Basic
<%@ 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  >
 <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>
          
C#
<%@ 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  >
 <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>
          
Visual Basic
<!-- 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="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)
                ' Set the number of rows displayed in the ListBox to be
                ' the number of items in the ListBoxCollection.
                ListBox1.Rows = ListBox1.Items.Count

                ' 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)
                ' 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)

                            ' Rebind the data to DataGrid1.
                            dv = new DataView(dt)
                            DataGrid1.DataSource = dv
                            DataGrid1.DataBind()
                        End If
                    End If
                Next item
            End Sub
        </script>
<html  >
    <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>
C#
<!-- 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. -->



...


<%@ 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)
            {
                // Set the number of rows displayed in the ListBox to be
                // the number of items in the ListBoxCollection.
                ListBox1.Rows = ListBox1.Items.Count;

                // 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)
            {
                // 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);

                            // Rebind the data to DataGrid1.
                            dv = new DataView(dt);
                            DataGrid1.DataSource = dv;
                            DataGrid1.DataBind();
                        }
                    }
                }
            }
        </script>
<html  >
    <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>

.NET Framework

Pris en charge dans : 4, 3.5, 3.0, 2.0, 1.1, 1.0

Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2

Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.
Tous les membres static (Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.
Contenu de la communauté   Qu'est-ce que le Contenu de la communauté ?
Ajouter du contenu RSS  Annotations
Processing
© 2012 Microsoft. Tous droits réservés. Conditions d'utilisation | Marques | Confidentialité
Page view tracker