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

105 Views Asked by At

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:

  • Listbox with Items:
  • 23 * - T41 EMK-D40, 62H7 BOHRFRAESEN, A0, C0
  • 24 CALL PGM \744
  • 25 TOOL CALL 41 Z S1600 F1000
  • 26 CALL LBL 500
  • 27 CYCL DEF 208 BOHRFRAESEN ~
  • Q200=+2 ;SICHERHEITS-ABST. ~
  • Q201=-55 ;TIEFE ~
  • Q206= AUTO ;VORSCHUB TIEFENZ. ~
  • Q334=+1 ;ZUSTELL-TIEFE ~
  • Q203=+0 ;KOOR. OBERFLAECHE ~
  • Q204=+50 ;2. SICHERHEITS-ABST. ~
  • Q335=+61 ;SOLL-DURCHMESSER ~
  • Q342=+39 ;VORGEB. DURCHMESSER ~
  • Q351=+1 ;FRAESART
  • 28 L Z+150 R0 FMAX
  • 29 L X+1138 Y-915 R0 FMAX
  • 30 L Z+22 R0 FMAX
  • 31 L M8 M3
  • 32 CALL LBL 14
  • 33 L Z+150 R0 FMAX M9 M5
  • 34 L Y+1200 Z+1200 R0 FMAX M92
  • 35 STOP

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;
                }
            }
        }
1

There are 1 best solutions below

3
samalk On

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)