Hi jiju,
I have created one sample that full-fill your requirement.
Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
Namespaces
You will need to import the following namespace.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB .Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Code
C#
string str = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
private void Form1_Load(object sender, EventArgs e)
{
this.GetAllRecords();
}
private void CountryChanged(object sender, EventArgs e)
{
int selectedItem = this.cbCountry.SelectedIndex;
if (selectedItem == 0)
{
this.GetAllRecords();
}
else
{
GetRecordsBasedOnCountry();
}
}
private void GetAllRecords()
{
using (SqlConnection con = new SqlConnection(str))
{
con.Open();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter("SELECT CustomerID,ContactName,City,Country FROM Customers", con);
DataTable dt = new DataTable();
da.Fill(dt);
dgvDetails.DataSource = dt;
con.Close();
}
}
private void GetRecordsBasedOnCountry()
{
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand("SELECT CustomerID,ContactName,City,Country FROM Customers WHERE Country = @Country", con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Country", this.cbCountry.SelectedItem);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
this.dgvDetails.DataSource = dt;
con.Close();
}
}
VB .Net
Private str As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Private Sub Form1_Load(sender As Object, e As EventArgs)
Me.GetAllRecords()
End Sub
Private Sub CountryChanged(sender As Object, e As EventArgs)
Dim selectedItem As Integer = Me.cbCountry.SelectedIndex
If selectedItem = 0 Then
Me.GetAllRecords()
Else
GetRecordsBasedOnCountry()
End If
End Sub
Private Sub GetAllRecords()
Using con As New SqlConnection(str)
con.Open()
Dim cmd As New SqlCommand()
Dim da As New SqlDataAdapter("SELECT CustomerID,ContactName,City,Country FROM Customers", con)
Dim dt As New DataTable()
da.Fill(dt)
dgvDetails.DataSource = dt
con.Close()
End Using
End Sub
Private Sub GetRecordsBasedOnCountry()
Using con As New SqlConnection(str)
Dim cmd As New SqlCommand("SELECT CustomerID,ContactName,City,Country FROM Customers WHERE Country = @Country", con)
con.Open()
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@Country", Me.cbCountry.SelectedItem)
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
Me.dgvDetails.DataSource = dt
con.Close()
End Using
End Sub
Screenshot
Hope this will help you.