Wadim
Wadim

Reputation: 23

C# Find specific string/text in ListBox Items and select it ALL

How can I select all the Items + the Item above the line I got found in my ListBox? For example... I have a ListBox with more than 200 Items:

I want to search for the string/text "M8 M3" and select all the Items + the Item above it (= line 30 + 31). In my case, unfortunately, only one item is selected. However, all items should be selected + the item above it. I hope someone can help. Thanks.

I try this code:

private void button13_Click(object sender, EventArgs e)
        {
            foreach (var content in listBox1.Items)
            {
                if (content.ToString().Contains("M8 M3"))
                {
                    listBox1.SelectedItem = content;
                    and select item above it...
                    break;
                }
            }
        }

Upvotes: 0

Views: 174

Answers (1)

samalk
samalk

Reputation: 21

You can use a for loop. If you match at index i, you can acccess i-1 for the previous element. However, consider what is supposed to happen if it is the first element that matches. (There is no previous element to grab)

Upvotes: 0

Related Questions