0

My Form defines a ContextMenuStrip:

Dim CMS As New ContextMenuStrip
Button1.ContextMenuStrip = CMS

There is also a Listview with 5 columns and some data:

ListView1.View = View.Details

How can I display the content of SubItems at index 1 and K of the first 5 Items of this ListView in a ContextMenuStrip?

CMS.Items.Clear()
For i As Integer = 0 To 5
    Dim line As String = ListView1.Items(i).SubItems(1).Text
    Dim line1 As String = ListView1.Items(i).SubItems(3).Text
    CMS.Items.Add(line & "|" & line1)
Next i

If the ListView contains are less than 5 ListViewItems, I get an exception.
If there is one ListViewItem in the ListView, then create one MenuItem.
If there are more than 5 ListViewItems, then display only values from the first 5 Items.

Jimi
  • 29,621
  • 8
  • 43
  • 61
Lider13
  • 47
  • 7

1 Answers1

0

You can define an interval of values in different ways.
Using the Min/Max methods of the Math class is probably simple and it can adapted to different scenarios. Personally, I used it quite often to validate the Maximum and Minimum values of Properties (e.g., you have a Property of Type Byte, so you may want to accept only values between 0 and 255).

  • You want to retrieve values from SubItems of the first 5 Items of a ListView. This is the Max() value.
  • The Min number of elements is determined by the content of the Items collection. It could be 0: in this case we don't want to iterate that collection, since it has nothing to give back. So, 0 is the Min() value
  • We need to consider that the indexer of these collections starts from 0.

The range of values is then:

Math.Max(Math.Min([Items Number], 5), 0) - 1

-1 since we start from 0: if we want Max 5 values, we iterate from 0 to (5 - 1) and if the Items collection has 0 elements, we iterate from 0 to (0 - 1), so we don't iterate the collection at all (the loop terminates right away).

You can rewrite your loop as:

For i As Integer = 0 To Math.Max(Math.Min(ListView1.Items.Count, 5), 0) - 1
    Dim line As String = ListView1.Items(i).SubItems(1).Text
    Dim line1 As String = ListView1.Items(i).SubItems(3).Text
    CMS.Items.Add(line & "|" & line1)
Next i
Jimi
  • 29,621
  • 8
  • 43
  • 61