Dynamically add items to Dropdownlist in ASP.Net

Mohammed Imtiyaz Jun 14, 2014

Demo

Dynamically add items to Dropdownlist in ASP.Net

Introduction

Some times we come across situations where we feel that some data is still required to accomplish some tasks. In my case, I came across a task where I was supposed to make a form where user can fill all the employee information at the same time. For instance if an employee belongs to some xyz city and that city is not displayed in the dropdownlist then users should be able to add that city to that dropdownlist without a full page postback. Below mentioned is a sample code which shows how to accomplish this task

CSS

First create a CSS to give a rich look to the form controls.

<title>Dynamically add items to Dropdownlist in ASP.Net</title>
<style type="text/css"> 
.inputTextBox
{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 13px;
    background-color: #fff;
    padding: 1px;
    border: solid 1px #ADACAC;
    color: #000000;
    width: 200px;
    height: 21px;
}
.inputDropDownList
{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 13px;
    height: 25px;
    background-color: #fff;
    padding: 1px;
    border: solid 1px #ADACAC;
    width: 204px;
    color: #000000;
}
.inputButton
{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 11px;
    background: lightgray;
    padding: 1px;
    border: solid 1px darkgray;
    width: 55px;
    height: 28px;
    color: #000;
    font-weight: bold;
}
</style>

HTML

<body>
    <form id="form1" runat="server"> 
/..
 You need to add to the form in order to work any ajax control properly.
../

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

<asp:UpdatePanel ID="updatePnlCity" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Label ID="lblCityExists" runat="server"  ForeColor="Red"></asp:label>
        <asp:Panel ID="pnlCity" runat="server">

        <table border="0" cellspacing="0"  cellpadding="0" width="500px">
        <tr>
            <td style="width: 30%"> Select City :</td>
            <td style="width: 35%">
                <asp:DropDownList ID="drpCity" runat="server" CssClass="inputDropDownList"></asp:DropDownList>
             </td>
             <td style="width: 3%"></td>
             <td style="width: 32%">
                 <asp:Button ID="btnCity" runat="server" Text="..." OnClick="btnCity_Click" CssClass="inputButton" />
             </td>
         </tr>
     </table>
</asp:Panel>
 
<asp:Panel ID="pnlAddCity" runat="server" Visible="false">
    <table  border="0">
        <tr>
            <td style="width: 30%"> Enter New City :</td>
                <td style="width: 35%">
                    <asp:TextBox ID="txtCity" runat="server" CssClass ="inputTextBox"></asp:Textbox>
                </td>
             <td style="width: 3%"></td>
             <td style="width: 32%">
                 <asp:Button ID="btnAdd"  runat="server" Text="Add" OnClick="btnAdd_Click" CssClass="inputButton" />
                 <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" CssClass="inputButton" />
             </td>
         </tr>
     </table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>

C# (Code-Behind)

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

public partial class _Default : System.Web.UI.Page
{
    // Connection String
    SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["CONN"]);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        BindCities();
        lblCityExists.Text = String.Empty; 
    }

    public void BindCities()
    {
        try
        {
            string strQuery = "SELECT id, city FROM tbl_city ORDER BY city";
            if (objConn.State != ConnectionState.Open) objConn.Open();
            
            SqlDataAdapter objDataAdapter = new SqlDataAdapter(strQuery, objConn);
            DataSet objDataset = new DataSet();
            objDataAdapter.Fill(objDataset);
            objDataset.Dispose();
            objConn.Close();

            if (objDataset.Tables[0].Rows.Count > 0)
            {
                objDataset.Dispose();
                drpCity.Items.Clear();
                drpCity.DataSource = objDataset;
                drpCity.DataTextField = "city";
                drpCity.DataValueField = "id";
                drpCity.DataBind();
                drpCity.Items.Insert(0, new ListItem("-- Select any city --", "0"));
            }
            else
            {
                drpCity.Items.Clear();
                drpCity.Items.Insert(0, new ListItem("-- Add New Record --", "0"));
            }
        }
        catch (Exception ex) {}
    }

    protected void btnCity_Click(object sender, EventArgs e)
    {
        pnlCity.Visible = false;
        pnlAddCity.Visible = true;
        txtCity.Focus();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            string strQuery = "EXEC sp_addCity '" + txtCity.Text.Trim() + "'";
            SqlCommand objCmd = new SqlCommand(strQuery, objConn);
            if (objConn.State != ConnectionState.Open) objConn.Open();

            SQLDataReader objDr = objCmd.ExecuteReader();
            if (objDr.Read())
            {
                if (objDr["already_exists"].ToString() == "0")
                {
                    string strId = objDr["unique_id"].ToString();
                    objDr.Close();
                    pnlCity.Visible = true;
                    pnlAddCity.Visible = false;
                    BindCities();
                    drpCity.SelectedValue = strId;
                    txtCity.Text = String.Empty;
                }
                else
                {
                    lblCityExists.Text = "'' " + txtCity.Text.Trim() + " ''" + " already  exists";
                }
            }
        }
        catch (Exception ex) {}
        finally {}
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        pnlCity.Visible = true;
        pnlAddCity.Visible = false;
    }
}