Hi.....
How do i set a listview to only add one item from a combobox?

Example:
In the text file containing the list are "Chicken, Beef, Buffalo", that already exists in listview is "Cow" then the listview will only add "Chicken, Buffalo".

i have here a code for adding items in a listview:

For Each ListedString As String In CType(iData.GetData(DataFormats.Text), String).Split(Environment.NewLine)
    For Each listItem As ListViewItem In MyListView1.Items
        If listItem.SubItems(2).Text = ListedString Then
            Return
        End If
    Next

    If UrlIsValid(ListedString) = True Then
        Dim lvi As New ListViewItem("Normal")
        lvi.SubItems.Add(MyListView1.Items.Count + 1)
        lvi.SubItems.Add(ListedString)
        lvi.SubItems.Add(GetFileNameFromURL(ListedString))
        MyListView1.Items.Add(lvi)
    End If
Next

Please, Help.

Thanks,

Bazzer Respeto

Recommended Answers

All 6 Replies

Unfortunately, there is no easy method to use for this. The Contains and ContainsKey (or even Find) methods do not search the listview for a given string. However, you can roll your own as follows:

Private Function InListView(lvw, text) As Boolean

    For Each item As ListViewItem In lvw.items
        If item.Text = text Then Return True
    Next

    Return False

End Function

If you pass this function a listview control and a string it will return True if that string appears in any cell in the first column, False otherwise. For example

Dim found As Boolean = InListView(MyListView, "Buffalo")

I dont get your point. What would you like to do exactly? Tell us the pattern why not adding a Beef as well?

I think the OP is saying that if (for example) Buffalo has already been added to the listview then it should not be added again.

thanks for the solution, Jim.
As I have tried before, the methods that you given didn't work.

Whatever Jim has given it works...add few more lines of code

Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click 'checked on button click
    Dim found As Boolean = InListView(ListView1, ComboBox1.Text)
    If found = True Then
        MsgBox("Exists")
    Else
        'MsgBox("No")
        ListView1.Items.Add(ComboBox1.Text)
    End If
End Sub

Private Function InListView(lvw, text) As Boolean
    For Each item As ListViewItem In lvw.items
        If item.Text = text Then Return True
    Next
    Return False
End Function

Thank you, it's worked.

I place the Jim code in wrong place, :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.