Click here to Skip to main content
15,879,326 members
Articles / Web Development / CSS
Tip/Trick

Insert and Bind Records from a dropdownlist using AJAX UpdatePanel

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
21 Feb 2013CPOL 16.5K   2   3
Insert and bind records from a dropdownlist using AJAX UpdatePanel

Insert and bind records from dropdownlist using ajax update panel

Introduction

Sometimes, 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. Mentioned below is a sample code which shows how to accomplish this task.

Using the Code

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

CSS
<title>Insert and bind records from dropdownlist using ajax update panel</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>

Body Contents

XML
<body>
    <form id="form1" runat="server">
    
    /..
	You need to add <asp:ScriptManager> 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><br /><br />
            <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%" align="center"></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" cellspacing="0" cellpadding="0" width="500px">
                    <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%" align="center"></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)

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.SqlClient;
using System.Data;
using System.Configuration;

public partial class _Default : System.Web.UI.Page 
{ 
    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;
    }
}

Points of Interest

  1. Insert and bind operations take place on a single click without a full page postback.
  2. Whatever you add will automatically be selected from the dropdownlist.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Saudi Arabia Saudi Arabia
Web Developer specializing in Web Design, Web Development and Web Programming

Portfolio: https://codecanyon.net/user/mimtiyaz/portfolio
Blog: http://www.ittutorials.in

Comments and Discussions

 
GeneralMy vote of 5 Pin
moeed iqbal18-Sep-13 22:31
moeed iqbal18-Sep-13 22:31 
GeneralRe: My vote of 5 Pin
mimtiyaz19-Sep-13 0:04
mimtiyaz19-Sep-13 0:04 
GeneralMy vote of 5 Pin
Mohammed Salman Qureshi8-Apr-13 0:19
Mohammed Salman Qureshi8-Apr-13 0:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.