0
votes

I have a bunch os items in lst1 which I want to put into lst2 but without repeating them on each ListBox.

Interface I'm using:

This is working, but you may need it to understand my doubt.

Dim dtTa_Enc As DataTable = New DataTable("Ta_Enc")
Dim dsTa As DataSet = New DataSet("Ta_E")

Dim adapter As New MySqlDataAdapter
Dim ds As DataSet = New DataSet

adapter.SelectCommand = New MySqlCommand
adapter.SelectCommand.Connection = connection
adapter.SelectCommand.CommandText = query

connection.Open()
adapter.Fill(ds, "tables")
connection.Close()

lst1.DataSource = ds.Tables("tables")
lst1.DisplayMember = "name"
lst1.ValueMember = "codta"

dtTa_Enc.Columns.Add("codta")
dtTa_Enc.Columns.Add("name")
dsTa.Tables.Add(dtTa_Enc)
lst2.DataSource = dsTa.Tables("Tables")
lst2.DisplayMember = "name"
lst2.ValueMember = "codta"
dtTa_Enc.Rows.Add(lst1.ValueMember, lst1.GetItemText(lst1.SelectedItem))

Doubt:
Now, The user presses a button to add his selected item of lst1 to lst2. Easy! However, what if he tries to add the same item. Can VB.Net stop him from doing it?

If not dtTa_Enc.find("codTa = " + lst1.valuemember) Then
    dtTa_Enc.Rows.Add(lstTabelas.ValueMember, lstTabelas.GetItemText(lstTabelas.SelectedItem))
End If
2
A modification of this code didn't work, but It was the best I found until now:DateTableBiohazard

2 Answers

0
votes

You can enumerate through your lst2 to determine whether any of the values match your selected item, lst1.SelectedItem.

So loop,

    Dim found As Boolean = False
    For Each itm As String in lst2.Items
        If itm = lst1.SelectedItem Then
            found = True
        End If
    Next
    If Not found Then
        'Add it.
    End If

Or you can simply use the Contains method:

    If Not lst2.Items.Contains(lst1.SelectedItem) Then
        'Add it.
    End if.
0
votes

Under the Add event handler, you could place some logic at the begining to prevent adding the repeated item.

    Dim lst1Selected As String = CType(lst1.SelectedItem, DataRowView)("name").ToString
    Dim flag As Integer = 0
    For Each item As Object In lst2.Items
        Dim istr As String = CType(item, DataRowView)("name").ToString
        If istr = lst1Selected Then
            flag = 1
            Exit For
        End If
    Next

    If flag = 1 Then
        Exit Sub
    End If