Hi PRA,
Multiple selection in combobox not possible, So instead of combobox use listbox.
Drag a ListBox from ToolBox and go to properties SelectionMode=MultiSimple for multi selection purpose.
Please refer below sample.
Namespaces
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Code
C#
public Form1()
{
InitializeComponent();
this.BindListBox();
}
private void BindListBox()
{
string constr = @"Data Source=.\SQL2005;DataBase=Test;UID=sa;PWD=password";
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);
lstCustomers.DataSource = dt;
lstCustomers.DisplayMember = "Name";
lstCustomers.ValueMember = "CustomerId";
}
}
}
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string name = "";
var row = lstCustomers.SelectedItems.Cast<DataRowView>();
foreach (var item in row)
{
name = item.Row[1].ToString();
string constr = @"Data Source=.\SQL2005;DataBase=Test;UID=sa;PWD=password";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Insert INTO Customers(Name) VALUES(@Name)", con))
{
cmd.Parameters.AddWithValue("@Name", name);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
MessageBox.Show("Record Inserted Successfully ");
}
VB.Net
Public Sub New()
InitializeComponent()
Me.BindListBox()
End Sub
Private Sub BindListBox()
Dim constr As String = "Data Source=.\SQL2005;DataBase=Test;UID=sa;PWD=pass"
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)
lstCustomers.DataSource = dt
lstCustomers.DisplayMember = "Name"
lstCustomers.ValueMember = "CustomerId"
End Using
End Using
End Using
End Sub
Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim name As String = ""
Dim row = lstCustomers.SelectedItems.Cast(Of DataRowView)()
For Each item In row
name = item.Row(1).ToString()
Dim constr As String = "Data Source=.\SQL2005;DataBase=Test;UID=sa;PWD=pass"
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("Insert INTO Customers(Name) VALUES(@Name)", con)
cmd.Parameters.AddWithValue("@Name", name)
con.Open()
con.Close()
End Using
End Using
Next
MessageBox.Show("Record Inserted Successfully ")
End Sub
Screenshot