Click here to Skip to main content
Click here to Skip to main content

Adding values to a dropdown using AJAX

, 6 Jun 2007
Rate this:
Please Sign up or sign in to vote.
How to add values to a dropdown using AJAX.

Screenshot - Image.jpg

Introduction

This article will describe how to add items to a dropdown using AJAX.

Background

I have used AjaxPro2.dll here and C# as the language. In the Value text box, type the value and press the Save button. The value will be saved in a SQL Server table and then retrieved from it and populated in the dropdown with out postback.

Using the code

Download the source code from the link above. Create a table in SQL Server named testing with the following fields: ID, Name. ID as identity Int, and Name varchar(50).

In the web.config file, inlude the name of the database in which you created the table named testing.

Run the application.

// In Code behind add the code like this
namespace MyAjaxSample
{
public partial class Testing :System.Web.UI.Page 
{
    public static string connectionString = 
      (string)ConfigurationManager.AppSettings["ConnectionString"]; 
    public DataSet ds = new DataSet(); 
    DBClass MyClass = new DBClass(); 
    public SqlDataAdapter ObjSDA; 
    public SqlCommand sc; 
    protected void Page_Load(object sender, EventArgs e) 
    {
        AjaxPro.Utility.RegisterTypeForAjax(typeof(Testing)); 
        if (!IsPostBack) 
        { 
            SqlConnection myConnection = new SqlConnection(connectionString); 
            ObjSDA = new SqlDataAdapter("Select * from Testing", myConnection);
            ObjSDA.Fill(ds); 
            DropDownList1.DataSource = ds; 
            DropDownList1.DataTextField = "Name"; 
            DropDownList1.DataValueField = "ID"; 
            DropDownList1.DataBind(); 
            DropDownList1.Items.Add("--Select table--");
            DropDownList1.SelectedIndex = DropDownList1.Items.Count - 1; 
        } 
    } 
    [AjaxPro.AjaxMethod] 
    public DataSet Inserting(string Name) 
    { 
        SqlConnection myConnection = new SqlConnection(connectionString); 
        string strQuery = "Insert into Testing Values('" + Name + "')"; 
        int res = MyClass.ExecuteQry(strQuery); 
        ObjSDA = new SqlDataAdapter("Select * from Testing", myConnection);
        ObjSDA.Fill(ds);
        return ds; 
    } 
} 
}

In the script side, you add the following code:

<script language="javascript">
function Inserting()
{
    if(document.getElementById("TextBox2").value == "")
    {
        alert('Enter the name'); 
    }
    else
    {
        var name = document.getElementById("TextBox2").value;
        MyAjaxSample.Testing.Inserting(name,InsertData_callback);
    }
}

function InsertData_callback(response)
{
    if (response != null && response.value != null)
    {
        var List = document.getElementById("DropDownList1");
        List.options.length = 0; 
        for (var i = 0; i < response.value.Tables[0].Rows.length; ++i)
        {
            List.options[List.options.length] = 
              new Option(response.value.Tables[0].Rows[i].Name,
              response.value.Tables[0].Rows[i].ID);
        }
        document.getElementById("TextBox2").value ="";
    }
}
</script>

Here is the database class:

namespace Ganesh
{
public class DBClass
{
    SqlConnection ObjCon = 
      new SqlConnection(
      ConfigurationManager.AppSettings["ConnectionString"]);
    public SqlCommand sc;
    public SqlDataAdapter sda;
    public SqlDataReader sdr;
    public DataSet ds;
    public int res;

    public DBClass()
    {
    //
    // TODO: Add constructor logic here
    //
    }

    public int ExecuteQry(string qry)
    {
        if (ObjCon.State == ConnectionState.Open) ObjCon.Close();
            ObjCon.Open();
        sc = new SqlCommand(qry, ObjCon);
        int res = sc.ExecuteNonQuery();
        ObjCon.Close();
        return res;
    }
}

Try this and let me know me your suggestions. Thanks.

License

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

About the Author

Ganesan Sankaran
Web Developer
India India
I'm Ganesan.S,
Software Engineer
Involved in developing MS applications for last 7 Yrs in VB,VB.NET,ASP.NET,Java Script and C#.NET lately into EPiServer and Ajax.

Comments and Discussions

 
QuestionJavaScript ?? PinmemberLautas6-Jun-07 22:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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 | Mobile
Web02 | 2.8.140709.1 | Last Updated 7 Jun 2007
Article Copyright 2007 by Ganesan Sankaran
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid