Click here to Skip to main content
12,291,230 members (62,351 online)
Click here to Skip to main content
Add your own
alternative version

Stats

9.2K views
247 downloads
2 bookmarked
Posted

Insert and Bind Records from a dropdownlist using AJAX UpdatePanel

, 21 Feb 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

<title>Insert and bind records from dropdownlist using ajax update panel</title>

Body Contents

<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)

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)

Share

About the Author

Imtiyaz_mi
Web Developer
Saudi Arabia Saudi Arabia
Visit http://www.ittutorials.in

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
moeed iqbal18-Sep-13 22:31
membermoeed iqbal18-Sep-13 22:31 
GeneralRe: My vote of 5 Pin
Imtiyaz_mi19-Sep-13 0:04
memberImtiyaz_mi19-Sep-13 0:04 
GeneralMy vote of 5 Pin
Mohammed Salman Qureshi8-Apr-13 0:19
memberMohammed 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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160518.1 | Last Updated 21 Feb 2013
Article Copyright 2013 by Imtiyaz_mi
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid