Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Adding values to a dropdown using AJAX

1.93/5 (5 votes)
6 Jun 2007CPOL 1   287  
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.

C#
// 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:

JavaScript
<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:

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