Skip to main content

Binding One DropDownList Based On Another DropDown List | Cascading dropdownlist in ASP.Net C#.Net

In this tutorial I am going to explain about how to load the one drop down list using another or cascading drop down list in ASP.Net  and C#.Net. It is achieved by passing the selected value of the one dropdown list as parameter to another drop down list.


Explanation:

For explanation purpose I have created three tables named Branches,Departments and employees. And I have inserted some sample records and also I wrote procedure to fetch values based on one drop down list value. Departments will get loaded based on branches selected value and employees will get loaded based on departments selected value. Below is the sql script used.

-- Branches Table Creation Script
CREATETABLE dbo.Branches
(
BranchId INTIDENTITY(1,1)PRIMARYKEY,
BranchName VARCHAR(100)NOTNULL
)
GO

--Inserting Sample Records In Branches Table
INSERTINTO dbo.Branches(BranchName)VALUES('Chennai')
INSERTINTO dbo.Branches(BranchName)VALUES('Mumbai')
INSERTINTO dbo.Branches(BranchName)VALUES('Delhi')

-- Department Table Creation Script
CREATETABLE dbo.Departments
(
DepartmentId INTIDENTITY(1,1)PRIMARYKEY,
DepartmentName VARCHAR(100)NOTNULL,
BranchId INTNOTNULL
)
GO

--Inserting Sample Records In Departments Table
INSERTINTO dbo.Departments(DepartmentName,BranchId)
VALUES('Designing',1)
INSERTINTO dbo.Departments(DepartmentName,BranchId)
VALUES('Designing',2)
INSERTINTO dbo.Departments(DepartmentName,BranchId)
VALUES('Designing',3)

INSERTINTO dbo.Departments(DepartmentName,BranchId)
VALUES('Development',1)
INSERTINTO dbo.Departments(DepartmentName,BranchId)
VALUES('Development',2)
INSERTINTO dbo.Departments(DepartmentName,BranchId)
VALUES('Development',3)

INSERTINTO dbo.Departments(DepartmentName,BranchId)
VALUES('Testing',1)
INSERTINTO dbo.Departments(DepartmentName,BranchId)
VALUES('Testing',2)
INSERTINTO dbo.Departments(DepartmentName,BranchId)
VALUES('Testing',3)

-- Employee Table Creation Script
CREATETABLE dbo.Employees
(
EmployeeId INTIDENTITY(1,1)PRIMARYKEY,
EmployeeName VARCHAR(100)NOTNULL,
DepartmentId INTNOTNULL
)
GO

--Inserting Sample Records In Branches Table
INSERTINTO dbo.Employees(EmployeeName,DepartmentId)
VALUES('Employee 1',1)
INSERTINTO dbo.Employees(EmployeeName,DepartmentId)
VALUES('Employee 2',1)
INSERTINTO dbo.Employees(EmployeeName,DepartmentId)
VALUES('Employee 3',1)

INSERTINTO dbo.Employees(EmployeeName,DepartmentId)
VALUES('Employee 4',2)
INSERTINTO dbo.Employees(EmployeeName,DepartmentId)
VALUES('Employee 5',2)
INSERTINTO dbo.Employees(EmployeeName,DepartmentId)
VALUES('Employee 6',2)

INSERTINTO dbo.Employees(EmployeeName,DepartmentId)
VALUES('Employee 7',3)
INSERTINTO dbo.Employees(EmployeeName,DepartmentId)
VALUES('Employee 8',3)
INSERTINTO dbo.Employees(EmployeeName,DepartmentId)
VALUES('Employee 9',3)


-- Procedure To Get All Branchs
CREATEPROC dbo.GetAllBranchs
AS
BEGIN
SETNOCOUNTON
SELECT BranchId,BranchName FROM dbo.Branches WITH(NOLOCK)
SETNOCOUNTOFF
END

-- Procedure To Get Departments By Branch Id
CREATEPROC dbo.GetAllDepartments
@BranchId INT
AS
BEGIN
SETNOCOUNTON
SELECT DepartmentId,DepartmentName FROM dbo.Departments
WITH(NOLOCK)WHERE BranchId=@BranchId
SETNOCOUNTOFF
END


-- Procedure To Get All Employees By Department Id
CREATEPROC dbo.GetEmployeesByDepartmentId
@DepartmentId INT
AS
BEGIN
SETNOCOUNTON
      SELECT EmployeeId,EmployeeName,DepartmentId FROM dbo.Employees
      WITH(NOLOCK)WHERE DepartmentId=@DepartmentId
SETNOCOUNTOFF
END

Now I have created a empty website and added a web form. And I have added three dropdown lists for loading Branches,departments and employees. Below is the html markup used.

<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%>

<!DOCTYPEhtml>

<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title></title>
</head>
<body>
<formid="form1"runat="server">
<divstyle="width: 900px; margin: 100px;">
<h2>Cascading Drop Down List</h2>
<table>
<tr>
<td>Branch Location</td>
<td>
<asp:DropDownListID="ddlBranch"Width="200"runat="server"AutoPostBack="true"OnSelectedIndexChanged="ddlBranch_OnSelectedIndexChanged">
<asp:ListItemValue=""></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Department</td>
<td>
<asp:DropDownListID="ddlDepartment"Width="200"runat="server"AutoPostBack="true"OnSelectedIndexChanged="ddlDepartment_OnSelectedIndexChanged">
<asp:ListItemValue=""></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Employees</td>
<td>
<asp:DropDownListID="ddlEmployees"Width="200"runat="server">
<asp:ListItemValue=""></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

In the code behind file include the necessary namespaces and include the following code.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
//Include this if it is not there
usingSystem.Configuration;
usingSystem.Data.SqlClient;
usingSystem.Data;

public partial class_Default : System.Web.UI.Page
{
String connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ToString();
protected voidPage_Load(object sender, EventArgs e)
    {
if (!IsPostBack)
BindBranchDetails();
    }

Protected void ddlBranch_OnSelectedIndexChanged(object sender, EventArgs e)
    {
BindDepartmentDetails();
    }
protectedvoidddlDepartment_OnSelectedIndexChanged(object sender, EventArgs e)
    {
BindEmployeeDetails();
    }

privatevoidBindBranchDetails()
    {
using (SqlConnectionsqlConn = newSqlConnection(connectionString))
        {
SqlCommandcmd = newSqlCommand();
cmd.CommandText = "dbo.GetAllBranchs";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
SqlDataAdapter adapter = newSqlDataAdapter(cmd);
DataSetdset = newDataSet();
adapter.Fill(dset, "Branch");
if (dset.Tables.Count> 0)
            {
DataTabledt = dset.Tables[0];
ddlBranch.DataSource = dt;
ddlBranch.DataTextField = "BranchName";
ddlBranch.DataValueField = "BranchId";
ddlBranch.DataBind();
ddlBranch.Items.Insert(0, newListItem("Select Branch", ""));

            }
        }
    }

privatevoidBindDepartmentDetails()
    {
using (SqlConnectionsqlConn = newSqlConnection(connectionString))
        {
SqlCommandcmd = newSqlCommand();
cmd.CommandText = "dbo.GetAllDepartments";
cmd.Parameters.AddWithValue("@BranchId", ddlBranch.SelectedValue);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
SqlDataAdapter adapter = newSqlDataAdapter(cmd);
DataSetdset = newDataSet();
adapter.Fill(dset, "Department");
if (dset.Tables.Count> 0)
            {
DataTabledt = dset.Tables[0];
ddlDepartment.DataSource = dt;
ddlDepartment.DataTextField = "DepartmentName";
ddlDepartment.DataValueField = "DepartmentId";
ddlDepartment.DataBind();
ddlDepartment.Items.Insert(0, newListItem("Select Department", ""));
ddlEmployees.Items.Clear();
ddlEmployees.Items.Insert(0, newListItem("", ""));
            }
        }
    }
privatevoidBindEmployeeDetails()
    {
using (SqlConnectionsqlConn = newSqlConnection(connectionString))
        {
SqlCommandcmd = newSqlCommand();
cmd.CommandText = "dbo.GetEmployeesByDepartmentId";
cmd.Parameters.AddWithValue("@DepartmentId", ddlDepartment.SelectedValue);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
SqlDataAdapter adapter = newSqlDataAdapter(cmd);
DataSetdset = newDataSet();
adapter.Fill(dset, "Employee");
if (dset.Tables.Count> 0)
            {
DataTabledt = dset.Tables[0];
ddlEmployees.DataSource = dt;
ddlEmployees.DataTextField = "EmployeeName";
ddlEmployees.DataValueField = "EmployeeId";
ddlEmployees.DataBind();
ddlEmployees.Items.Insert(0, newListItem("Select Employee", ""));
            }
        }
    }
}

Now if you run the application based on the one dropdownlist another list will get loaded. Below is the screenshot of the output.

Output of Binding One DropDownList Based On Another DropDown List | Cascading dropdownlist in ASP.Net C#.Net
Source Code:
Source code of Binding One DropDownList Based On Another DropDown List | Cascading dropdownlist in ASP.Net C#.Net

You May Also Like...

Comments

  1. You Could Have Used One common Method. Lots duplicate Codes Are Used Here

    ReplyDelete
    Replies
    1. Thanks for your valuable comment. Will do it henceforth. You mean fetching data from the database right?

      Delete

Post a Comment

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     { ...

Puzzles for kids - 12 Days Of Christmas

According to the traditional song, on the first day of Christmas (25th December), my true love sent to me: . A partridge in a pair tree On the second day of Christmas (26th December), my true love sent to me THREE presents: . Two turtle doves . A partridge in a pear tree On the third day of Christmas (27th December and so on) my true love sent to me SIX presents: . Three French hens . Two turtle doves . A partridge in a pear tree This carries on until the the twelfth day of Christmas, when my true love sends me: Twelve drummers drumming Eleven pipers piping Ten lords a-leaping Nine ladies dancing Eight maids a-milking Seven swans a-swimming Six geese a-laying Five gold rings Four calling birds Three French hens Two turtle doves A partridge in a pear tree After the twelve days of Christmas are over, how many presents has my true love sent me altogether? Our Solution: 1 + 3 + 6 + 10 + 15 + 21 + 28 + 36 + 45 + 55 + 66 + 78 = 364 presents Which is really interesting when you think ...

Asp.Net DataTable Manipulation - Add, Update,Delete & Sort DataTable in C#.Net & VB.Net

In the asp.net developer's life it is very common to come across the datatable manipulation. So here i have decided to explain the datatable manipulation like adding records to datatable, editing and updating datatable records,deleting records from datatable based on the condition and finally sorting datatable based on columns.