Add ListItem in DropDownList asp.net c# Example:

DropDownList example: 

How to add dynamically ListItem in DropDownList, Asp.netdropdownlist web control enables user to select a particular item from given list item. Dropdownlist refers to collection of items in List. List item have two properties Text properties and Value properties. A text property gives the content which display on web browser and Value represent a hidden field text related to specific list item. We can populate dropdownlist from various data in List. And we also can add item in list of dropdownlist controlmanually. 

 In this post we consider following example code demonstrates that how can we add listitem in dropdownlist control byprogrammatically (dynamically using c# or csharp code). Here we create a script section on web page top section. We also consider a button with click event and one textbox control in form. When user click the button control, web page post to web server, and create a listiem for dropdownlist. New listitem Text generate from textbox control’s user input text.

AddListItem_in_DropDownList.aspx



Code Example of DropDowmlist”

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>DropDownList example: how to add ListItem dynamically</title>
    <script runat="server"> 
        protected void Button1_Click(object sender, System.EventArgs e)
        {
            DropDownList1.Items.Add(new ListItem(TextBox1.Text));
            Response.Write("Item Added: " + TextBox1.Text);
        } 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center">
        Example of DropDownlist Insert item dynamically:<br />
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem>Listitem</asp:ListItem>
            <asp:ListItem> Listitem1</asp:ListItem>
            <asp:ListItem> Listitem2</asp:ListItem>
            <asp:ListItem> Listitem3</asp:ListItem>
            <asp:ListItem>List item4</asp:ListItem>
            <asp:ListItem> Listitem5</asp:ListItem>
            <asp:ListItem> item6/asp:ListItem>
        </asp:DropDownList>
        <hr />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <hr />
        <asp:Button ID="Button1" runat="server" Text="Add Item" OnClick="Button1_Click" />
        <hr />
    </div>
    </form>
</body>
</html>

Just Copy the code and past on asp.net web page ,run and see the result :

Other Related Post In this Asp.net Tutorial: 

Comments