Question Check if item exists before adding it

ud2008

Well-known member
Joined
Jul 5, 2010
Messages
148
Programming Experience
Beginner
I have a datagridview and I can add a selected item from the datagridview to a listview by double click the grid.
This does work, but I want to check if the item I try to add does already exists in the listview.

I have the following code, but this doesn't work:
VB.NET:
Private Sub DataGridViewX1_DoubleClick(sender As System.Object, e As System.EventArgs) Handles DataGridViewX1.DoubleClick
        Dim lvItem As ListViewItem = ListView1.FindItemWithText(DataGridViewX1.SelectedCells(1).Value.ToString, True, 0)
        If (lvItem IsNot Nothing) Then
            Dim lvi As New ListViewItem
            lvi.Text = DataGridViewX1.SelectedCells(1).Value.ToString
            lvi.SubItems.Add(DataGridViewX1.SelectedCells(6).Value.ToString)
            ListView1.Items.Add(lvi)

            If ListView1.Items.Count > 0 Then
                Timer1.Start()
                ListView1.Enabled = True
                PrintSonglistButton.Enabled = True
                ClearAllButton.Enabled = True
                ClearSelectedButton.Enabled = True
                linesModified = True
            End If
        Else
            MessageBox.Show("Title already exists in the songlist!")
        End If
    End Sub

Please help.
 
No it doesn't work and I'm totally baffled as to why you think it would. Timer? Try

If ListView1.Items.Contains(lvi) Then etc.

... preferably before you add the item.
 
ud2008 said:
Dim lvItem As ListViewItem = ListView1.FindItemWithText(DataGridViewX1.SelectedCells(1).Value.ToString, True, 0)
If (lvItem IsNot Nothing) Then
The return value is Nothing if an item is not found, your code would only add a new item if an item is found (return value ISNOT Nothing).
Also, are you sure subitems should be included in the search, as your current code does?
Dunfiddlin said:
If ListView1.Items.Contains(lvi) Then etc.
OP is trying to see if an item with specified text exist, not to check object reference for an existing ListViewItem.
 
Dunfiddlin, please, you're just being argumentative. The "item" OP is checking for is a string....
 
Back
Top