Hi smile,
Refer elow 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 EmployeeId, Country FROM Employees", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
DataRow row = dt.NewRow();
row[0] = 0;
row[1] = "Please select";
dt.Rows.InsertAt(row, 0);
this.comboBox1.DataSource = dt;
this.comboBox1.DisplayMember = "Country";
this.comboBox1.ValueMember = "EmployeeId";
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue.GetType() != typeof(DataRowView))
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT EmployeeId, Country FROM Employees WHERE Country =@Country", con))
{
cmd.Parameters.AddWithValue("@Country", comboBox1.Text);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
this.clbCustomers.DataSource = dt;
this.clbCustomers.DisplayMember = "EmployeeId";
this.clbCustomers.ValueMember = "EmployeeId";
}
}
}
}
}
VB.Net
Private Sub Form1_Load_1(ByVal sender As Object, ByVal e As EventArgs)
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT EmployeeId, Country FROM Employees", con)
Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
Dim row As DataRow = dt.NewRow()
row(0) = 0
row(1) = "Please select"
dt.Rows.InsertAt(row, 0)
Me.comboBox1.DataSource = dt
Me.comboBox1.DisplayMember = "Country"
Me.comboBox1.ValueMember = "EmployeeId"
End Using
End Using
End Using
End Sub
Private Sub comboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
If comboBox1.SelectedValue.[GetType]() <> GetType(DataRowView) Then
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT EmployeeId, Country FROM Employees WHERE Country =@Country", con)
cmd.Parameters.AddWithValue("@Country", comboBox1.Text)
Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
Me.clbCustomers.DataSource = dt
Me.clbCustomers.DisplayMember = "EmployeeId"
Me.clbCustomers.ValueMember = "EmployeeId"
End Using
End Using
End Using
End If
End Sub
Screenshot