Here i am going to explain how to add an item dynamically in a DropDownList Control.
Introduction
In this article, i am going to show the different ways of
dynamic addition of an item in a DropDownList control.
1. Using jquery(HTML controls)
2. Using jquery(ASP.NET controls)
3. Using javascript
4. Using AppendDataBoundItems
Using jquery(HTML controls)
Here, I have used HTML Select,HTML Input(Text) and HTML Input(Submit) controls.
Now typed a flower name in the TextBox and clicked on the button.
Instantly, the flower name is added in the list.
Default.aspx
Here i have used
jquery-1.2.6.js . This is easily and freely downloadable.
To download jquery-1.2.6.js plz click on the following link:
http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.2.6.js&can=2&q=
Place the script tag within the head tag.
Now, place the following within the div tag. Here, the 4 items have been taken beforehand. The value of
txtEnterFlower is added to the list on the click of a button. With the
onclick event,
function() method is called
and the value of
txtEnterFlower is appended in the list.
jquery-1.2.6.js present in the
Scripts folder.
Using jquery (ASP.NET controls)
The same technique has been used here. Only difference is, here i have used ASP.NET dropdownlist control without causing a postback. Here also, i have used the same script tag using jquery(mentioned above).
Type the name of a flower and click the button
Add Item. The name of the flower is added to the dropdownlist control immediately.
The following shows the use of ASP.NET dropdownlist control.
using javascript
Here, I have used Html button and textbox and ASP.NET DropDownList controls.
Now, type the name, which you want to insert in the dropdownlist
The final output looks like this. That means, on the click of a button, the text is added to the dropdownlist.
Default3.aspx
On the click of a button,
insertanitem() method is called. The id of
txtddl and
ddl are stored in
Mytext and
ddlItems respectively. An option element is created. Value of
Mytext is initialized in option . And finally, option is added to the
dropdownlist control. And this adds an item to the dropdownlist control dynamically using javascript.
Using AppendDataBoundItems
In order to set the first item of an ASP.NET dropdownlist as
Select, we can use a new Boolean property named
AppendDataBoundItems.
AppendDataBoundItems is set to
True.One more thing to do. A default
ListItem is added. And finally, the dropdownlist is bound with the database named
User.
Output:
The dropdownlist shows the
Select.
Now i have typed the following details and clicked the button
Add Item. The dropdownlist is showing that the item is inserted instantly.
Table tblUser. Data in the dropdownlist is shown from this table.
Default4.aspx
Default4.aspx.cs
btnAddItem_Click Event
Conclusion
Happy Programming!