Add items to dropdownlist using TextBox in ASP.NET

In this article i will show you how to add items in DropdownList with value. In general way if we add items in the list then you can add only add Text in the list. Like
Dropdownlist1.Items.add(string Text);
But you want to add text with value from Textbox in Dropdownlist then check the below example:



Source

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        ENTER ITEMS :
        <asp:TextBox ID="TextBox1" runat="server" Width="209px"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="ADD ITEMS" />
        <br />
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
    </form>
 
     

</body>
</html>

Code Behind
 protected void Button1_Click(object sender, EventArgs e)
    {
        if (TextBox1.Text.Trim()!="")
        {
            DropDownList1.Items.Add(new ListItem(TextBox1.Text, TextBox1.Text));
        }
    }

Comments

Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites