Hi RPA,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used three tables Countries, States and Cities that you can download using the link given below.
Download SQL file
Form Design
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Code
C#
public Form1()
{
InitializeComponent();
dgCountries.DataSource = GetData("SELECT CountryId,CountryName FROM Countries");
}
private void dgCountries_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
int countryId = Convert.ToInt32(dgCountries.CurrentRow.Cells[0].Value);
dgStates.DataSource = GetData("SELECT StateId,StateName FROM States WHERE CountryId = " + countryId);
}
}
private void dgStates_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
int stateId = Convert.ToInt32(dgStates.CurrentRow.Cells[0].Value);
dgCities.DataSource = GetData("SELECT CityId,CityName FROM Cities WHERE StateId = " + stateId);
}
}
private DataTable GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
VB.Net
Public Sub New()
InitializeComponent()
dgCountries.DataSource = GetData("SELECT CountryId,CountryName FROM Countries")
End Sub
Private Sub dgCountries_CellClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
If e.RowIndex > -1 Then
Dim countryId As Integer = Convert.ToInt32(dgCountries.CurrentRow.Cells(0).Value)
dgStates.DataSource = GetData("SELECT StateId,StateName FROM States WHERE CountryId = " & countryId)
End If
End Sub
Private Sub dgStates_CellClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
If e.RowIndex > -1 Then
Dim stateId As Integer = Convert.ToInt32(dgStates.CurrentRow.Cells(0).Value)
dgCities.DataSource = GetData("SELECT CityId,CityName FROM Cities WHERE StateId = " & stateId)
End If
End Sub
Private Function GetData(ByVal query As String) As DataTable
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim cmd As SqlCommand = New SqlCommand(query)
Using con As SqlConnection = New SqlConnection(conString)
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
Screenshot