i have a listbox that users can add Countries Names into it anytime. now i need to only add new data to check if the data is new then insert it to sql. my code not work:
For Each i As String In listbox1.Items
Dim sql = "select * From Countries where CountryName=N'" & i & "'"
Dim adp As New SqlClient.SqlDataAdapter(sql, SQlconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
If dt.Rows.Count = 0 Then
Dim dr = dt.NewRow
dr!CountryName = i
dt.Rows.Add(dr)
Dim cmd As New SqlClient.SqlCommandBuilder(adp)
adp.Update(dt)
End If
Next
If you're loading the existing names from the database in the first place then there's no need for you to check anything. Simply query the database to populate a DataTable
and bind that to the ListBox
. When the user adds a new country, add it to the DataTable
and it will automatically show up in the ListBox
. When it's time to save, just use the same data adapter to save the DataTable
and only the new records will be saved.