Hi smile,
Refer below sample.
Namespaces
C#
using System.Data.SqlClient;
VB.Net
Imports System.Data.SqlClient
Code
C#
private void Form1_Load_1(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name FROM Customers", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
this.clbCustomers.DataSource = dt;
this.clbCustomers.DisplayMember = "Name";
this.clbCustomers.ValueMember = "CustomerId";
}
}
}
}
private void Insert(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd;
foreach (object item in clbCustomers.CheckedItems)
{
DataRowView row = item as DataRowView;
cmd = new SqlCommand("INSERT INTO TestCustomer(CustomerId, Name) VALUES(@CustomerId, @Name)", con);
cmd.Parameters.AddWithValue("@CustomerId", row["CustomerId"]);
cmd.Parameters.AddWithValue("@Name", row["Name"]);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
cmd = new SqlCommand("SELECT * FROM TestCustomer", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
VB.Net
Private Sub Form1_Load_1(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT CustomerId, Name FROM Customers", con)
Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
Me.clbCustomers.DataSource = dt
Me.clbCustomers.DisplayMember = "Name"
Me.clbCustomers.ValueMember = "CustomerId"
End Using
End Using
End Using
End Sub
Private Sub Insert(ByVal sender As Object, ByVal e As EventArgs)
Dim con As SqlConnection = New SqlConnection(constr)
Dim cmd As SqlCommand
For Each item As Object In clbCustomers.CheckedItems
Dim row As DataRowView = TryCast(item, DataRowView)
cmd = New SqlCommand("INSERT INTO TestCustomer(CustomerId, Name) VALUES(@CustomerId, @Name)", con)
cmd.Parameters.AddWithValue("@CustomerId", row("CustomerId"))
cmd.Parameters.AddWithValue("@Name", row("Name"))
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Next
cmd = New SqlCommand("SELECT * FROM TestCustomer", con)
Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
dataGridView1.DataSource = dt
End Sub
Screenshot