Comment : ajouter des fonctions de recherche à un contrôle ListView

Mise à jour : novembre 2007

Souvent, lorsque vous utilisez une longue liste d'éléments dans un contrôle ListView, vous souhaitez offrir des fonctions de recherche à l'utilisateur. Le contrôle ListView offre cette fonction de deux façons différentes : par correspondance de texte et par recherche d'emplacement.

La méthode FindItemWithText vous permet d'effectuer une recherche de texte sur un ListView dans une vue Liste ou en mode Détails, à l'aide d'une chaîne de recherche et d'un index de début et de fin facultatif. En revanche, la méthode FindNearestItem vous permet de rechercher un élément dans un ListView dans une vue Icônes ou dans un affichage en mosaïque, à l'aide d'un jeu de coordonnées x- et y- et un sens de la recherche.

Pour rechercher un élément à l'aide de texte

  1. Créez un ListView avec Details ou List affecté à la propriété View, puis remplissez ListView avec des éléments.

  2. Appelez la méthode FindItemWithText, en passant le texte de l'élément que vous souhaitez trouver.

  3. L'exemple de code suivant montre comment créer un ListViewde base, le remplir avec des éléments, puis utiliser l'entrée de texte de l'utilisateur pour rechercher un élément dans la liste.

Private textListView As New ListView()
Private WithEvents searchBox As New TextBox()

Private Sub InitializeTextSearchListView() 
    searchBox.Location = New Point(150, 20)
    textListView.Scrollable = True
    textListView.Width = 80
    textListView.Height = 50

    ' Set the View to list to use the FindItemWithText method.
    textListView.View = View.List

    ' Populate the ListView with items.
    textListView.Items.AddRange(New ListViewItem() { _
        New ListViewItem("Amy Alberts"), _
        New ListViewItem("Amy Recker"), _
        New ListViewItem("Erin Hagens"), _
        New ListViewItem("Barry Johnson"), _
        New ListViewItem("Jay Hamlin"), _
        New ListViewItem("Brian Valentine"), _
        New ListViewItem("Brian Welker"), _
        New ListViewItem("Daniel Weisman")})

    ' Add the controls to the form.
    Me.Controls.Add(textListView)
    Me.Controls.Add(searchBox)

End Sub

Private Sub searchBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs) _
    Handles searchBox.TextChanged

    ' Call FindItemWithText with the contents of the textbox.
    Dim foundItem As ListViewItem = _
        textListView.FindItemWithText(searchBox.Text, False, 0, True)

    If (foundItem IsNot Nothing) Then
        textListView.TopItem = foundItem
    End If

End Sub
private ListView textListView = new ListView();
private TextBox searchBox = new TextBox();
private void InitializeTextSearchListView()
{
    searchBox.Location = new Point(10, 60);
    textListView.Scrollable = true;
    textListView.Width = 80;
    textListView.Height = 50;

    // Set the View to list to use the FindItemWithText method.
    textListView.View = View.List;

    // Populate the ListViewWithItems
    textListView.Items.AddRange(new ListViewItem[]{ 
        new ListViewItem("Amy Alberts"), 
        new ListViewItem("Amy Recker"), 
        new ListViewItem("Erin Hagens"), 
        new ListViewItem("Barry Johnson"), 
        new ListViewItem("Jay Hamlin"), 
        new ListViewItem("Brian Valentine"), 
        new ListViewItem("Brian Welker"), 
        new ListViewItem("Daniel Weisman") });

    // Handle the TextChanged to get the text for our search.
    searchBox.TextChanged += new EventHandler(searchBox_TextChanged);

    // Add the controls to the form.
    this.Controls.Add(textListView);
    this.Controls.Add(searchBox);

}

private void searchBox_TextChanged(object sender, EventArgs e)
{
    // Call FindItemWithText with the contents of the textbox.
    ListViewItem foundItem =
        textListView.FindItemWithText(searchBox.Text, false, 0, true);
    if (foundItem != null)
    {
        textListView.TopItem = foundItem;

    }
}
private:
    ListView^ textListView;
    TextBox^ searchBox;

private:
    void InitializeTextSearchListView()
    {
        textListView = gcnew ListView();
        searchBox = gcnew TextBox();
        searchBox->Location = Point(150, 20);
        textListView->Scrollable = true;
        textListView->Width = 100;

        // Set the View to list to use the FindItemWithText method.
        textListView->View = View::List;

        // Populate the ListViewWithItems
        textListView->Items->AddRange(gcnew array<ListViewItem^>{
            gcnew ListViewItem("Amy Alberts"),
            gcnew ListViewItem("Amy Recker"),
            gcnew ListViewItem("Erin Hagens"),
            gcnew ListViewItem("Barry Johnson"),
            gcnew ListViewItem("Jay Hamlin"),
            gcnew ListViewItem("Brian Valentine"),
            gcnew ListViewItem("Brian Welker"),
            gcnew ListViewItem("Daniel Weisman") });

        // Handle the TextChanged to get the text for our search.
        searchBox->TextChanged += gcnew EventHandler(this, 
            &Form1::searchBox_TextChanged);

        // Add the controls to the form.
        this->Controls->Add(textListView);
        this->Controls->Add(searchBox);
    }

private:
    void searchBox_TextChanged(Object^ sender, EventArgs^ e)
    {
        // Call FindItemWithText with the contents of the textbox.
        ListViewItem^ foundItem =
            textListView->FindItemWithText(searchBox->Text, false, 0, true);
        if (foundItem != nullptr)
        {
            textListView->TopItem = foundItem;
        }
    }

Pour rechercher un élément à l'aide des coordonnées x- et y-

  1. Créez un ListView avec SmallIcon ou LargeIcon affecté à la propriété View, puis remplissez ListView avec des éléments.

  2. Appelez la méthode FindNearestItem, en passant les coordonnées x- et y- voulus et dans quel sens que vous aimeriez rechercher.

  3. L'exemple de code suivant montre comment créer une icône de base ListView, le remplir avec des éléments et capturer l'événement MouseDown pour rechercher l'élément le plus proche dans un sens de recherche vers le haut.

Private WithEvents iconListView As New ListView()
Private previousItemBox As New TextBox()


Private Sub InitializeLocationSearchListView()
    previousItemBox.Location = New Point(150, 20)

    ' Create an image list for the icon ListView.
    iconListView.LargeImageList = New ImageList()

    ' Add an image to the ListView large icon list.
    iconListView.LargeImageList.Images.Add(New Bitmap(GetType(Control), "Edit.bmp"))

    ' Set the view to large icon and add some items with the image
    ' in the image list.
    iconListView.View = View.SmallIcon
    iconListView.Items.AddRange(New ListViewItem() { _
        New ListViewItem("Amy Alberts", 0), _
        New ListViewItem("Amy Recker", 0), _
        New ListViewItem("Erin Hagens", 0), _
        New ListViewItem("Barry Johnson", 0), _
        New ListViewItem("Jay Hamlin", 0), _
        New ListViewItem("Brian Valentine", 0), _
        New ListViewItem("Brian Welker", 0), _
        New ListViewItem("Daniel Weisman", 0)})

    Me.Controls.Add(iconListView)
    Me.Controls.Add(previousItemBox)
End Sub

Sub iconListView_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _
    Handles iconListView.MouseDown

    ' Find the next item up from where the user clicked.
    Dim foundItem As ListViewItem = _
    iconListView.FindNearestItem(SearchDirectionHint.Up, e.X, e.Y)

    ' Display the results in a textbox.
    If (foundItem IsNot Nothing) Then
        previousItemBox.Text = foundItem.Text
    Else
        previousItemBox.Text = "No item found"
    End If


End Sub
ListView iconListView = new ListView();
TextBox previousItemBox = new TextBox();

private void InitializeLocationSearchListView()
{
    previousItemBox.Location = new Point(150, 20);

    // Create an image list for the icon ListView.
    iconListView.LargeImageList = new ImageList();
    iconListView.Height = 400;

    // Add an image to the ListView large icon list.
    iconListView.LargeImageList.Images.Add(
        new Bitmap(typeof(Control), "Edit.bmp"));

    // Set the view to large icon and add some items with the image
    // in the image list.
    iconListView.View = View.LargeIcon;
    iconListView.Items.AddRange(new ListViewItem[]{
        new ListViewItem("Amy Alberts", 0), 
        new ListViewItem("Amy Recker", 0), 
        new ListViewItem("Erin Hagens", 0), 
        new ListViewItem("Barry Johnson", 0), 
        new ListViewItem("Jay Hamlin", 0), 
        new ListViewItem("Brian Valentine", 0), 
        new ListViewItem("Brian Welker", 0), 
        new ListViewItem("Daniel Weisman", 0) });
    this.Controls.Add(iconListView);
    this.Controls.Add(previousItemBox);

    // Handle the MouseDown event to capture user input.
   iconListView.MouseDown +=
       new MouseEventHandler(iconListView_MouseDown);
    //iconListView.MouseWheel += new MouseEventHandler(iconListView_MouseWheel);   
}

void iconListView_MouseDown(object sender, MouseEventArgs e)
{

    // Find the an item above where the user clicked.
    ListViewItem foundItem =
        iconListView.FindNearestItem(SearchDirectionHint.Up, e.X, e.Y);

    // Display the results in a textbox..
    if (foundItem != null)
        previousItemBox.Text = foundItem.Text;
    else
        previousItemBox.Text = "No item found";
}
    ListView^ iconListView;
    TextBox^ previousItemBox;

private:
    void InitializeLocationSearchListView()
    {
        previousItemBox = gcnew TextBox();
        iconListView = gcnew ListView();
        previousItemBox->Location = Point(150, 20);

        // Create an image list for the icon ListView.
        iconListView->SmallImageList = gcnew ImageList();

        // Add an image to the ListView small icon list.
        iconListView->SmallImageList->Images->Add(
            gcnew Bitmap(Control::typeid, "Edit.bmp"));

        // Set the view to small icon and add some items with the image
        // in the image list.
        iconListView->View = View::SmallIcon;
        iconListView->Items->AddRange(gcnew array<ListViewItem^>{
            gcnew ListViewItem("Amy Alberts", 0),
            gcnew ListViewItem("Amy Recker", 0),
            gcnew ListViewItem("Erin Hagens", 0),
            gcnew ListViewItem("Barry Johnson", 0),
            gcnew ListViewItem("Jay Hamlin", 0),
            gcnew ListViewItem("Brian Valentine", 0),
            gcnew ListViewItem("Brian Welker", 0),
            gcnew ListViewItem("Daniel Weisman", 0) });
         this->Controls->Add(iconListView);
         this->Controls->Add(previousItemBox);

         // Handle the MouseDown event to capture user input.
         iconListView->MouseDown += gcnew MouseEventHandler(
             this, &Form1::iconListView_MouseDown);
    }

    void iconListView_MouseDown(Object^ sender, MouseEventArgs^ e)
    {
        // Find the next item up from where the user clicked.
        ListViewItem^ foundItem = iconListView->FindNearestItem(
            SearchDirectionHint::Up, e->X, e->Y);

        // Display the results in a textbox..
        if (foundItem != nullptr)
        {
            previousItemBox->Text = foundItem->Text;
        }
        else
        {
            previousItemBox->Text = "No item found";
        }
    }

Voir aussi

Tâches

Comment : ajouter et supprimer des éléments avec le contrôle ListView Windows Forms

Référence

Vue d'ensemble du contrôle ListView (Windows Forms)

ListView

FindItemWithText

FindNearestItem

Autres ressources

ListView, contrôle (Windows Forms)