Dynamic DropDown Retrieval

Posted by Chvrsri under C# category on | Points: 40 | Views : 2653
This program allows a particular user to Dynamically update the values of drop down list. For Example we genrally see in many websites for regsitration purposes there would be a drop down box for Country , So now if we select a country in that the page must dynamically update and must fetch the states related to that country. My Sample program will explain how to do this simple task.
//In Default.aspx.cs page type the below code :

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)
SqlConnection con = new SqlConnection("server=ServerName;user id=UserName;password=Password;database=DatabaseName");

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Country", con);
DataSet ds = new DataSet();
da.Fill(ds, "Country");

ddl1.DataSource = ds;
ddl1.DataTextField = "CountryName";
ddl1.DataValueField = "CountryID";


protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
SqlConnection con = new SqlConnection("server=ServerName;user id=UserName;password=Password;database=DatabaseName");
string sri = ddl1.SelectedValue.ToString();
SqlDataAdapter da = new SqlDataAdapter("select * from State where CountryID='" + sri + "'", con);
DataSet ds1 = new DataSet();
da.Fill(ds1, "State");
ddl2.DataSource = ds1;
ddl2.DataTextField = "StateName";
ddl2.DataValueField = "CountryID";

//The actual Design page is Default.aspx the Code is given below :

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<form id="form1" runat="server">
<asp:DropDownList ID="ddl1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddl1_SelectedIndexChanged">

<asp:DropDownList ID="ddl2" runat="server"></asp:DropDownList>




Note :
1. In my backend i have 2 tables which are COUNTRY and STATE
2.ddl1,ddl2 are the Respective id's of the drop down lists

Cheers !! Happy Coding !!!

Comments or Responses

Login to post response