ListBox, classe (System.Windows.Forms)

Bibliothèque de classes .NET Framework 
ListBox, classe 

Représente un contrôle Windows pour afficher une liste d'éléments.

Espace de noms : System.Windows.Forms
Assembly : System.Windows.Forms (dans system.windows.forms.dll)

SyntaxeSyntaxe


Visual Basic (Déclaration)
<ComVisibleAttribute(True)> _
<ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)> _
Public Class ListBox
    Inherits ListControl


Visual Basic (Utilisation)
Dim instance As ListBox


C#
[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] 
public class ListBox : ListControl


C++
[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType::AutoDispatch)] 
public ref class ListBox : public ListControl


J#
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */ 
public class ListBox extends ListControl


JScript
ComVisibleAttribute(true) 
ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) 
public class ListBox extends ListControl
NotesNotes

Le contrôle ListBox permet d'afficher une liste d'éléments dans laquelle l'utilisateur peut sélectionner en cliquant. Un contrôle ListBox peut fournir des sélections uniques ou multiples suivant la valeur de la propriété SelectionMode. ListBox fournit également la propriété MultiColumn, qui permet d'afficher des éléments dans plusieurs colonnes plutôt que dans une liste verticale. Cela permet au contrôle d'afficher les éléments de façon plus visible et évite à l'utilisateur de faire défiler la liste pour afficher un élément.

Généralement, Windows gère la tâche consistant à dessiner les éléments à afficher dans ListBox. Vous pouvez utiliser la propriété DrawMode et gérer les événements MeasureItem et DrawItem pour substituer le dessin automatique de Windows et dessiner vous-même les éléments. Vous pouvez utiliser des contrôles ListBox owner-drawn pour afficher des éléments de hauteur variable, des images ou une couleur ou une police différentes pour le texte de chaque élément de la liste. Les propriétés HorizontalExtent, GetItemHeight et GetItemRectangle vous aident à dessiner vos propres éléments.

Outre les fonctionnalités d'affichage et de sélection, ListBox fournit des fonctionnalités qui permettent d'ajouter efficacement des éléments à ListBox et de rechercher du texte dans les éléments de la liste. Les méthodes BeginUpdate et EndUpdate vous permettent d'ajouter un grand nombre d'éléments au ListBox sans repeindre le contrôle chaque fois qu'un élément est ajouté à la liste. Les méthodes FindString et FindStringExact vous permettent de rechercher dans la liste un élément qui contient une chaîne spécifique.

Les propriétés Items, SelectedItems et SelectedIndices permettent d'accéder aux trois collections utilisées par ListBox. Le tableau suivant décrit les trois collections utilisées par ListBox ainsi que leur utilisation dans le contrôle.

 

Classe de collection

Utilisation dans ListBox

ListBox.ObjectCollection

Contient tous les éléments présents dans le contrôle ListBox.

ListBox.SelectedObjectCollection

Contient une collection des éléments sélectionnés qui est un sous-ensemble des éléments contenus dans le contrôle ListBox.

ListBox.SelectedIndexCollection

Contient une collection des index sélectionnés, qui est un sous-ensemble des index de ListBox.ObjectCollection. Ces index spécifient les éléments qui sont sélectionnés.

Les trois exemples suivants sont des exemples des trois collections indexées prises en charge par la classe ListBox.

Le tableau suivant décrit comment ListBox.ObjectCollection stocke les éléments de ListBox ainsi que leur état de sélection dans un exemple de ListBox.

 

Index

Élément

État de sélection dans l'objet ListBox

0

objet1

Non sélectionné

1

objet2

Sélectionné

2

objet3

Non sélectionné

3

objet4

Sélectionné

4

objet5

Sélectionné

À partir de ListBox.ObjectCollection décrit dans le tableau ci-dessus, le tableau suivant décrit comment ListBox.SelectedObjectCollection est affiché.

 

Index

Élément

0

objet2

1

objet4

2

objet5

À partir de ListBox.ObjectCollection décrit dans le tableau ci-dessus, le tableau suivant décrit comment ListBox.SelectedIndexCollection est affiché.

 

Index

Index de l'élément

0

1

1

3

2

4

La méthode Add de la classe ListBox.ObjectCollection permet d'ajouter des éléments à ListBox. La méthode Add peut accepter n'importe quel objet quand un élément est ajouté à ListBox. Quand un objet est ajouté à ListBox, le contrôle utilise le texte défini dans la méthode ToString de l'objet jusqu'à ce qu'un nom de membre dans l'objet soit spécifié dans la propriété DisplayMember. En plus de l'ajout d'éléments à l'aide de la méthode Add de la classe ListBox.ObjectCollection, vous pouvez également ajouter des éléments en utilisant la propriété DataSource de la classe ListControl.

RemarqueRemarque

Si vous avez un ListBox, ComboBox ou CheckedListBox sur un formulaire Windows de base et souhaitez modifier les collections de chaînes de ces contrôles dans un formulaire Windows dérivé, les collections de chaînes de ces contrôles dans le formulaire Windows de base doivent être vides. Si les collections de chaînes ne sont pas vides, elles sont mises en lecture seule lorsque vous dérivez un autre formulaire Windows.

ExempleExemple

L'exemple de code suivant illustre la création d'un contrôle ListBox qui affiche plusieurs éléments dans des colonnes et dans lequel plusieurs éléments peuvent être sélectionnés dans la liste. Le code de l'exemple ajoute 50 éléments à ListBox en utilisant la méthode Add de la classe ListBox.ObjectCollection puis sélectionne trois éléments dans la liste avec la méthode SetSelected. Le code affiche ensuite les valeurs de la collection ListBox.SelectedObjectCollection (par l'intermédiaire de la propriété SelectedItems) et de ListBox.SelectedIndexCollection (par l'intermédiaire de la propriété SelectedIndices). Cet exemple requiert que le code se trouve dans et soit appelé à partir de Form.



Visual Basic
Private Sub button1_Click(sender As Object, e As System.EventArgs)
    ' Create an instance of the ListBox.
    Dim listBox1 As New ListBox()
    ' Set the size and location of the ListBox.
    listBox1.Size = New System.Drawing.Size(200, 100)
    listBox1.Location = New System.Drawing.Point(10, 10)
    ' Add the ListBox to the form.
    Me.Controls.Add(listBox1)
    ' Set the ListBox to display items in multiple columns.
    listBox1.MultiColumn = True
    ' Set the selection mode to multiple and extended.
    listBox1.SelectionMode = SelectionMode.MultiExtended
    
    ' Shutdown the painting of the ListBox as items are added.
    listBox1.BeginUpdate()
    ' Loop through and add 50 items to the ListBox.
    Dim x As Integer
    For x = 1 To 50
        listBox1.Items.Add("Item " & x.ToString())
    Next x
    ' Allow the ListBox to repaint and display the new items.
    listBox1.EndUpdate()
    
    ' Select three items from the ListBox.
    listBox1.SetSelected(1, True)
    listBox1.SetSelected(3, True)
    listBox1.SetSelected(5, True)
       
    ' Display the second selected item in the ListBox to the console.
    System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems(1).ToString())
    ' Display the index of the first selected item in the ListBox.
    System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices(0).ToString())
End Sub



C#
private void button1_Click(object sender, System.EventArgs e)
{
   // Create an instance of the ListBox.
   ListBox listBox1 = new ListBox();
   // Set the size and location of the ListBox.
   listBox1.Size = new System.Drawing.Size(200, 100);
   listBox1.Location = new System.Drawing.Point(10,10);
   // Add the ListBox to the form.
   this.Controls.Add(listBox1);
   // Set the ListBox to display items in multiple columns.
   listBox1.MultiColumn = true;
   // Set the selection mode to multiple and extended.
   listBox1.SelectionMode = SelectionMode.MultiExtended;
 
   // Shutdown the painting of the ListBox as items are added.
   listBox1.BeginUpdate();
   // Loop through and add 50 items to the ListBox.
   for (int x = 1; x <= 50; x++)
   {
      listBox1.Items.Add("Item " + x.ToString());
   }
   // Allow the ListBox to repaint and display the new items.
   listBox1.EndUpdate();
      
   // Select three items from the ListBox.
   listBox1.SetSelected(1, true);
   listBox1.SetSelected(3, true);
   listBox1.SetSelected(5, true);

   // Display the second selected item in the ListBox to the console.
   System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems[1].ToString());
   // Display the index of the first selected item in the ListBox.
   System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices[0].ToString());             
}



C++
void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
   
   // Create an instance of the ListBox.
   ListBox^ listBox1 = gcnew ListBox;
   
   // Set the size and location of the ListBox.
   listBox1->Size = System::Drawing::Size( 200, 100 );
   listBox1->Location = System::Drawing::Point( 10, 10 );
   
   // Add the ListBox to the form.
   this->Controls->Add( listBox1 );
   
   // Set the ListBox to display items in multiple columns.
   listBox1->MultiColumn = true;
   
   // Set the selection mode to multiple and extended.
   listBox1->SelectionMode = SelectionMode::MultiExtended;
   
   // Shutdown the painting of the ListBox as items are added.
   listBox1->BeginUpdate();
   
   // Loop through and add 50 items to the ListBox.
   for ( int x = 1; x <= 50; x++ )
   {
      listBox1->Items->Add( String::Format( "Item {0}", x ) );

   }
   listBox1->EndUpdate();
   
   // Select three items from the ListBox.
   listBox1->SetSelected( 1, true );
   listBox1->SetSelected( 3, true );
   listBox1->SetSelected( 5, true );
   
   // Display the second selected item in the ListBox to the console.
   System::Diagnostics::Debug::WriteLine( listBox1->SelectedItems[ 1 ] );
   
   // Display the index of the first selected item in the ListBox.
   System::Diagnostics::Debug::WriteLine( listBox1->SelectedIndices[ 0 ] );
}



J#
private void button1_Click(Object sender, System.EventArgs e)
{
    // Create an instance of the ListBox.
    ListBox listBox1 = new ListBox();

    // Set the size and location of the ListBox.
    listBox1.set_Size(new System.Drawing.Size(200,100));
    listBox1.set_Location(new System.Drawing.Point(10,10));

    // Add the ListBox to the form.
    this.get_Controls().Add(listBox1);

    // Set the ListBox to display items in multiple columns.
    listBox1.set_MultiColumn(true);

    // Set the selection mode to multiple and extended.
    listBox1.set_SelectionMode(SelectionMode.MultiExtended);

    // Shutdown the painting of the ListBox as items are added.
    listBox1.BeginUpdate();

    // Loop through and add 50 items to the ListBox.
    for (int x = 1; x <= 50; x++) {
        listBox1.get_Items().Add(("Item" + (new Integer(x)).ToString()));
    }

    // Allow the ListBox to repaint and display the new items.
    listBox1.EndUpdate();

    // Select three items from the ListBox.
    listBox1.SetSelected(1,true);
    listBox1.SetSelected(3,true);
    listBox1.SetSelected(5,true);

    // Display the second selected item in the ListBox to the console.
    System.Diagnostics.Debug.WriteLine
        (listBox1.get_SelectedItems().get_Item(1).ToString());

    // Display the index of the first selected item in the ListBox.
    System.Diagnostics.Debug.WriteLine((new Integer
        (listBox1.get_SelectedIndices().get_Item(0))).ToString());
} //button1_Click


JScript
private function button1_Click(sender : Object, e : System.EventArgs)
{
   // Create an instance of the ListBox.
   var listBox1 : ListBox = new ListBox();
   // Set the size and location of the ListBox.
   listBox1.Size = new System.Drawing.Size(200, 100);
   listBox1.Location = new System.Drawing.Point(10,10);
   // Add the ListBox to the form.
   this.Controls.Add(listBox1);
   // Set the ListBox to display items in multiple columns.
   listBox1.MultiColumn = true;
   // Set the selection mode to multiple and extended.
   listBox1.SelectionMode = SelectionMode.MultiExtended;
 
   // Shutdown the painting of the ListBox as items are added.
   listBox1.BeginUpdate();
   // Loop through and add 50 items to the ListBox.
   for (var x : int = 1; x <= 50; x++)
   {
      listBox1.Items.Add("Item " + x.ToString());
   }
   // Allow the ListBox to repaint and display the new items.
   listBox1.EndUpdate();
      
   // Select three items from the ListBox.
   listBox1.SetSelected(1, true);
   listBox1.SetSelected(3, true);
   listBox1.SetSelected(5, true);

   // Display the second selected item in the ListBox to the console.
   System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems[1].ToString());
   // Display the index of the first selected item in the ListBox.
   System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices[0].ToString());             
}

Hiérarchie d'héritageHiérarchie d'héritage
System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
       System.Windows.Forms.Control
         System.Windows.Forms.ListControl
          System.Windows.Forms.ListBox
             System.Windows.Forms.CheckedListBox
Sécurité des threadsSécurité des threads
Les membres statiques publics (Shared en Visual Basic) de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.
Plates-formesPlates-formes

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition

Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.

Informations de versionInformations de version

.NET Framework

Prise en charge dans : 2.0, 1.1, 1.0

.NET Compact Framework

Prise en charge dans : 2.0, 1.0
Voir aussiVoir aussi

Ces informations proviennent du site de http://msdn2.microsoft.com
Source de cette page : http://msdn2.microsoft.com/fr-fr/library/system.windows.forms.listbox.aspx

Réseaux sociaux

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

 

Nuage de mots clés

9 mots clés dont 0 définis manuellement (plus d'information...).

Avertissement

Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

 

Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
Aucun commentaire pour cette page

© Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-5642
Document créé le 30/10/06 00:32, dernière modification le Vendredi 17 Juin 2011, 12:11
Source du document imprimé : http://www.gaudry.be/dotnet-rf-system.windows.forms.listbox.html Document affiché 1 fois ce mois de Juin.
St.Gaudry©07.01.02
Outils (masquer)
||
Recherche (afficher)
Recherche :

Utilisateur (masquer)
Apparence (afficher)
Stats (afficher)
15832 documents
452 astuces.
549 niouzes.
3099 definitions.
447 membres.
8115 messages.

Document genere en :
0,51 seconde

Mises à jour :
Mises à jour du site
Citation (masquer)
CHANDAIL : Vêtement que doit porter un enfant lorsque sa mère a froid.

Pierre Desproges
 
l'infobrol
Nous sommes le Vendredi 01 Juin 2012, 05:42, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)