Bind DropDownList using Asp .Net C#

Hi this post explains how to bind "DownDownList  with sql data using as asp .Net c#".For this tutorial I am using Customers Table from Northwind database.To download Northwind data base follow the link .

The Html Markup

The Following Html Markup consist drop down list ans status label to show selection  value.

<div>
        <asp:Label ID="lblCity" runat="server" Text="City:"></asp:Label>
        <asp:DropDownList ID="ddlCity" runat="server" 
            onselectedindexchanged="ddlCity_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
            <br />
            <br />
        <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
    </div>

C# Code:

Following code bind the data to the dropdown list.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.BindDropDownList();
        }
    }

    private void BindDropDownList()
    {
        SqlConnection conn = Connection();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "SELECT DISTINCT City from Customers";
        cmd.Connection = this.Connection();
        DataTable dTable = new DataTable(); 
        SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd);
        sqlAdapter.Fill(dTable);
        ddlCity.DataSource = dTable;        
        ddlCity.DataTextField = "City";
        ddlCity.DataValueField = "City";
        ddlCity.DataBind();
        ddlCity.Items.Insert(0, new ListItem("--SELECT CITY--", "-1"));
    }

//Connection String object creation
    private SqlConnection Connection()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        SqlConnection conn = new SqlConnection(constr);
        return conn;
    }


DropDownList Selection Index Changed:

The following code get the selected item from the dropdown list and shows it on the label.

protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblStatus.Text = "Selected City:" + ddlCity.SelectedItem.Text;        
    }

ConnectionString:

Place the following connection string in the web config file.

<connectionStrings>
    <add name="constr" connectionString="Data Source=(local);Initial Catalog=NORTHWND;Integrated Security=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>

Output:




Download Source Code



No comments :

Post a Comment