How to bind Dropdownlist Dynamically from database in asp.net with c# Example like when you select state name then corresponding cites are binded in to second dropdownlist

Introduction:-

How to bind Dropdownlist Dynamically from database in asp.net with c# like when you select state name then corresponding cites are binded in to second dropdownlist.

Here is the screen shot what i am talking about.


source code(in asp.net):-




<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        State<asp:DropDownList ID="ddstate" runat="server" AutoPostBack="True"
            onselectedindexchanged="ddstate_SelectedIndexChanged">
       </asp:DropDownList>
        <br />
        City<asp:DropDownList ID="ddcity" runat="server">
       </asp:DropDownList>
    </div>
    </form>
</body>
</html>

code behind(in C#):-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    static string str = @"your connection string";
    public static SqlConnection con = new SqlConnection(str);
     protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            BindState(ddstate);
        }
    }
    protected void ddstate_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindCity(ddstate.SelectedItem.Text,ddcity);
    }
   public void BindState(DropDownList ddstate)
    {
        ddstate.DataSource = Data_of_Grid("SELECT * FROM aby_State"); ;
        ddstate.DataTextField = "state";
        ddstate.DataValueField = "stateid";
        ddstate.DataBind();
        ddstate.Items.Insert(0, new ListItem("<Select State>", "0"));
    }

   public void BindCity(string state, DropDownList ddcity)
    {
        ddcity.DataSource = Data_of_Grid("SELECT aby_City.* FROM aby_City INNER JOIN aby_State ON aby_City.stateid = aby_State.stateid WHERE(aby_State.state = '" + state + "')");

        ddcity.DataTextField = "city";

        ddcity.DataValueField = "cityid";

        ddcity.DataBind();

        ddcity.Items.Insert(0, new ListItem("<Select City>", "0"));

    }

    public DataTable Data_of_Grid(string q)

    {
        DataTable dt = new DataTable();
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlCommand cmd = new SqlCommand(q, con);
            SqlDataAdapter sd = new SqlDataAdapter();
            sd.SelectCommand = cmd;
           sd.Fill(dt);

        }
        catch (Exception err)
        {
            //TODO
        }
        finally
        {
            con.Close();
        }
       return dt;
    }
}

Post a Comment