csharp

Perform Cascading ComboBox in Windows Forms using C#

In this article we will learn how to Perform Cascading ComboBox in Windows Forms using C#.The two ComboBox i.e for country and state will be populated from sql server database in Windows Forms(WinForms) application using C#.
Here I have to show complete Demo of how to Implement/Perform Cascading ComboBox in Windows Forms(WinForms) application Using C#.
Screen Shot Describe theoutput after run the project.

1. Cascading Combobox Complete Demo
Go to=>Visual Studio=>File Project. looks like screenshot


You Can Change the Name of project and browse your project at different location as you wish.After that press ok.
2. On Form1.cs[Design] page drag and drop two label and two combobox.looks like scrrenshot

Change the label1 text with “Country” and label2 text with “State”.
3. DataBase
Create two table tblCountry and tblState
[php]
Create table tblCountry(
Countryid int primary key identity(1,1),
CountryName varchar(30)
)

/*Create State Table*/

Create table tblState(
StateId int primary key identity(1,1),
StateName varchar(30),
Countryid int foreign key references tblCountry(Countryid)
)
[/php]
Note: we set the foreign key to provide a relation between them table this foreign key follows Country Id based on this ID we select state (“Suppose that whenever select India only India’s State show”)

4.Insert data into tblCountry and tblState Table
[php]
/*Insert data into CountryTable*/
insert into tblCountry(CountryName) values(‘India’),(‘Pakistan’),(‘America’)

/*Insert data into State Table*/
insert into tblState(StateName,Countryid) values(‘Bihar’,1)
insert into tblState(StateName,Countryid) values(‘UP’,1)
insert into tblState(StateName,Countryid) values(‘Gujrat’,1)
insert into tblState(StateName,Countryid) values(‘Lahore’,2)
insert into tblState(StateName,Countryid) values(‘Karachi’,2)
insert into tblState(StateName,Countryid) values(‘Newyork’,2)
insert into tblState(StateName,Countryid) values(‘Texas’,3)
insert into tblState(StateName,Countryid) values(‘Washington’,3)
[/php]

5. Create stored procedure to getting the data from a country and state table sp_tblCountry_get and sp_tblState_get are procedure Name
[php]
/*Procedure for select data from Country Table*/

create proc sp_tblCountry_get
as
begin
Select * from tblCountryCountry
end
/*Procedure for Select data from State table*/
create proc sp_tblState_get
@Countryid int
as
begin
Select * from tblState where Countryid=@ountryid
end

[/php]
6.Open app.config file and establish a connection with a database.

[php]
<connectionStrings>
<add name="DBCS" connectionString="data source=.; initial catalog=CascadingDemo;integrated security=true"/>
</connectionStrings>
[/php]
Note
In initial catalog write Database Name
In data source you can simply write (.) /your server name/(local)
Integrated security for Authentication

7. Code
Open Form1.cs page(Mouse Right Click on Form1.cs[Design] page select View Code or simply click F7 key).We will see we will be entered in the code part of the Form1.cs page.Simply write the code here.
[php]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

// need to import the following namespaces.
using System.Data.SqlClient;
using System.Configuration;

namespace CascadingDemo
{
public partial class Form1 : Form
{
/// <summary>
/// Here i have create a sqlconnection object to interact with database
/// Here "DBCS" taking from app.config page
/// </summary>

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
DataRow dataRow;

public Form1()
{
InitializeComponent();
BindComboCountry();
}

/// <summary>
/// Here i have create method "BindComboCountry()" for bind Country
/// cmbCountry is a name of combobox.
/// its neccesary property its used when you use this control
/// in your form.
/// "sp_tblCountry_get" is a procedure name
/// Populating the Country Combobox
/// </summary>
public void BindComboCountry()
{
//open the SqlConnection
con.Open();
//
//The Following code uses an sqlcommand based on the sqlconnection
//
SqlCommand cmd = new SqlCommand("sp_tblCountry_get", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
dataRow = dt.NewRow();
dataRow.ItemArray = new object[] { 0, "–Select Country–" };
dt.Rows.InsertAt(dataRow,0);
cmbCountry.ValueMember = "Countryid";
cmbCountry.DisplayMember = "CountryName";
cmbCountry.DataSource = dt;
}

/// <summary>
/// Here i have to create event.Like Normal combobox selected indexChanged event.
/// you can use this event whenever you have to require some action/operation on selected index
/// changed of combobox.you have to fired this event and perform some action
/// whatever you are select country store this selected country id in Country id variable
/// This countryId pass as parameter in BindComboState() Method
/// </summary>

private void cmbCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbCountry.SelectedValue != null)
{
int countryId = Convert.ToInt32(cmbCountry.SelectedValue.ToString());
BindComboState(countryId);
}
}

/// <summary>
/// Here i have create method "BindComboState()" for bind State
/// pass one parameter based on selection of Country Id
/// cmbState is a name of combobox.
/// its neccesary property its used when you use this control
/// in your form.
/// "sp_tblState_get" is a procedure name
/// Populating the State Combobox
/// </summary>
public void BindComboState(int countryId)
{
//open the SqlConnection
con.Open();
//
//The Following code uses an sqlcommand based on the sqlconnection
//
SqlCommand cmd = new SqlCommand("sp_tblState_get", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Countryid", countryId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
dataRow = dt.NewRow();
dataRow.ItemArray = new object[] { 0, "–Select State–" };
dt.Rows.InsertAt(dataRow, 0);
cmbState.ValueMember = "StateId";
cmbState.DisplayMember = "StateName";
cmbState.DataSource = dt;
}
}
}

[/php]

Hope You like this.Any Suggestion and question related to this article please comment.Have a nice day.

Leave a Reply

Your email address will not be published.