Click here to Skip to main content
15,891,704 members
Articles / Web Development / ASP.NET
Article

Two DropDownList with Client Call-Back

Rate me:
Please Sign up or sign in to vote.
3.88/5 (6 votes)
13 Mar 2008CPOL3 min read 25.9K   493   18   2
An article on how to fill in a list by another list's client-selected items
ddlCallBack

Introduction

I wanted to learn how to create a list that was populated by selected items in another list (like dropDownList), since I enjoyed working with them on other people's websites. After much search on the web, I succeeded in finding that one of my own books: ASP.NET 2.0 MVP Hacks and Tips had the answers.

Background

I don't know whether you know what callBack is or not, however, I suggest reading a related chapter of book.

Using the Code

If you want to see the result on your own machine, you can download the above (.zip) file .

ddlCallBack.aspx.cs

C#
string ICallbackEventHandler.GetCallbackResult()
{
    StringBuilder sb1 = new StringBuilder();

    try
    {
        SqlConnection sqlC = new SqlConnection(
            ConfigurationManager.ConnectionStrings["cstr1"].ConnectionString);
        SqlCommand sqlCom = new SqlCommand(
            "select customerID,customerName from customers where itemID = @itemIDi",
            sqlC);

        sqlCom.Parameters.Add(new SqlParameter("@itemIDi", SqlDbType.Int));
        sqlCom.Parameters["@itemIDi"].Value = this.earg;


        sqlC.Open();
        SqlDataReader sqlDR = sqlCom.ExecuteReader(CommandBehavior.CloseConnection);

        while (sqlDR.Read())
        {
            sb1.Append(sqlDR["customerID"]);
            sb1.Append("|");
            sb1.Append(sqlDR["customerName"]);
            sb1.Append("||");

        }
        sqlDR.Close();
    }
    catch(Exception e1)
    {
        throw new ApplicationException(e1.Message.ToString());

    }


    return sb1.ToString();

}

The above code [GetCallbackResult() method], is where the results are returned from the server code to client script via the "return" statement. In other words, when a client changes a selected-item in "items" list, and the onchange event is fired, the selected-value is passed from the client to the server through the eventArgument variable that causes the class variable earg to be set in RaiseCallbackEvent:

C#
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
   this.earg = eventArgument;
}

Then the GetCallbackResult() method gets related customers from customer table:

C#
select customerID,customerName from customers where itemID = @itemIDi

and makes a string (by stringBuilder class) in which customerID separated by "|" from customerName and both separated by "||" from next customer's information :

while (sqlDR.Read())
{
    sb1.Append(sqlDR["customerID"]);
    sb1.Append("|");
    sb1.Append(sqlDR["customerName"]);
    sb1.Append("||");
}

In Client-Side

When the resulting string that contains related customer name & ID are returned back from the database, they are passed to the client-side function named: clientResponse. The name that defined the third argument of the GetCallbackEventReference method (a method to which the onchange event of the items list refers), the clientResponse client-side function gets it, and splits it to its parts and sets the rows variable:

C#
var rows = result.split('||');

Then, by following the for loop, this is done for each element of rows: separate customerID from customerName and create an option tag:

C#
document.createElement("option");

Where its value is customerID and its displaying customerName:

for (var i = 0; i < rows.length - 1; ++i)
{
    // Split each record into two fields.
    var fields = rows[i].split('|');
    var customerID = fields[0];
    var customerName = fields[1];
    // Create the list item.
    var option = document.createElement("option");
    // Store the ID in the value attribute.
    option.value = customerID;
    // Show the description in the text of the list item.
    option.innerHTML = customerName;
    lstCustomers.appendChild(option);
}

And finally, appends a new option element to ddlCustomers in JavaScript named lstCustomers by:

JavaScript
var lstCustomers = document.forms[0].elements['ddlCustomers'];

What Happens when the Client Selects an Item

When a client selects an item from ddlItems, the onchange event of this control occurs. This event refers to a client-side script by:

C#
ddlItems.Attributes["onchange"] = eventRef;

In reality, the onchange event refers to a string (named eventRef) that is a reference to a client-side script by itself:

C#
string eventRef = Page.ClientScript.GetCallbackEventReference(this,
 "document.all['ddlItems'].value", "clientResponse", "null", "ErrorFunction", true);

Continuing the story, when the client selects an item, the ID of a selected item (that is the value of selected-item in ddlItems) will be passed to the server method RaiseCallbackEvent and this method sets the value of a class variable earg by passing the value from the client as eventArgument parameter, then the server method GetCallbackResult gets related customers from the database by:

C#
SqlConnection sqlC = new SqlConnection(
    ConfigurationManager.ConnectionStrings["cstr1"].ConnectionString);
SqlCommand sqlCom = new SqlCommand(
    "select customerID,customerName from customers where itemID = @itemIDi", sqlC);

sqlCom.Parameters.Add(new SqlParameter("@itemIDi", SqlDbType.Int));
sqlCom.Parameters["@itemIDi"].Value = this.earg;


sqlC.Open();
SqlDataReader sqlDR = sqlCom.ExecuteReader(CommandBehavior.CloseConnection);

and builds the string sb1 by:

C#
while (sqlDR.Read())
{
    sb1.Append(sqlDR["customerID"]);
    sb1.Append("|");
    sb1.Append(sqlDR["customerName"]);
    sb1.Append("||");

}

and passes this string to the client by:

C#
return sb1.ToString();

if there is an error, this error will be passed to the client by:

C#
catch(Exception e1)
{
    throw new ApplicationException(e1.Message.ToString());

}

and the client will show it by:

C#
function ErrorFunction(error , ctx)
{
    alert("The Event Failed Becuase " + error);
}

Finally, the above code contains what will occur on the client-side to fill the customers list named: ddlCustomers.

History

I guess there is no need for an updated version, however, if you have any problem or request that I can solve by the help of GOD, please send me a mail or comment.

License

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


Written By
Web Developer i.r iran
Iran (Islamic Republic of) Iran (Islamic Republic of)
an iranian asp.net 2.0 web developer

Comments and Discussions

 
GeneralMy vote of 4 Pin
Yannick25-Sep-12 1:30
Yannick25-Sep-12 1:30 
GeneralMy vote of 2 Pin
RajaAhmed1-Feb-09 22:22
RajaAhmed1-Feb-09 22:22 

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.