Home  »  Articles  »  ASP.Net  »

Fill Dropdownlist dynamically and handle onselectedindexchanged event

 Posted By : Manoranjan SahooPosted Date : 02/11/2010 07:19:16 AM Category : ASP.Net Points : 5 (Rs 2.00)

Hello Friends,

Here i am going to show how to fill DropDownList dynamically and how to handle onselectedindexchanged event.

To fill dropdownlist follow below steps :

Steps :

1. Create one sample webpage and add 2 dropdownlist with name ddlCountry and ddlState.

Note : Here i am going to fill States as per selected country.

2. follow the below code to add 2 dropdownlist

Code :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
       Country: <asp:DropDownList ID="ddlCountry" runat="server"  AutoPostBack ="true"
        </asp:DropDownList><br />
        State : <asp:DropDownList ID="ddlState" runat="server" >
        </asp:DropDownList><br />


3. Now the step to make the method to fill the dropdownlist. As i have to fill the state as per selected country in this example, We have to fill ddlCountry at the time of page load. Then we have to fill State after selecting a Country. So we have to make a method first to fill the drop downlist. Follow below code.

Code :

void fill_ddl(string strSQL,string tablename,DropDownList ddl)
         if (cn.State == ConnectionState.Closed) { cn.Open(); }
         SqlDataAdapter sda = new SqlDataAdapter(strSQL, cn);
         DataSet ds = new DataSet();
         sda.Fill(ds, tablename);
         if (ds.Tables[0].Rows.Count > 0)
              DataRow dtr;
              int i = 0;
              while (i < ds.Tables[0].Rows.Count)
                  dtr = ds.Tables[0].Rows[i];
                  ddl.Items.Add(new ListItem(dtr[0].ToString(), dtr[1].ToString()));

   catch (Exception ex)


4. Now time to call the above fill method at the time of pageload to fill Country

To call from pageload follow below code :

if (!IsPostBack)

     string strquery = "select countryname , code from tblCountry_master order by countryname";
     fill_ddl(strquery, "Country",ddlCountry);



5. Now time to handle onselectedindexchanged event of ddlCountry dropdownlist. put the below code inside onselectedindexchanged event.

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        string strquery = "select statename, code from tblState_master where code='"+ ddlCountry.SelectedItem.Value +"' order by statename";
        fill_ddl(strquery, "State", ddlState );

6. Now just run the code and test the output.

Thank You.

No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.