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 create log files in C#.Net|Asp.Net

Introduction: In my previous article I have explained about how to create, delete and check whether the directory exists using C#.Net . In this article I am going to explain about  How to create log files in C#.Net. Explanation: Log files are useful to track any runtime errors and exceptions in all the applications. Below code will code will get the Message and Pagename as the input and creates the log file in that date. For that first i have imported below two namespaces.

Dynamically programmatically add contols at run time Asp.Net

Introduction: In my previous article I have explained about What is View State? How to Store and retrieve values from View State . In this article I am going to explain how to add controls programmatically on run time. Explanation: This example adds a text box and button to a Web Forms page at run time. It also dynamically binds an event handler to the button's   Click   event. The handler displays the values of the dynamically generated text box. The controls are added into a   Panel   Web server control, which acts as a placeholder. The controls are separated in the panel with line breaks (HTML <BR> elements), which are added to the panel using the   LiteralControl   control.

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)     { ...