Saturday, 22 March 2014

How to add an item to a drop down list in asp.net

Drop down is used to display data in the form of list but at a time only one item will display. It just behaves as the input control for User and in form. There are many ways to add the items in drop down; Direct defined in HTML file, add items from C# file and add items from datasource.
@Directly Add items from HTML file


Adding item from item list. Adding the items through item list
Add Directly :      <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Text="First" Selected=True  Value=1>First</asp:ListItem>
        <asp:ListItem Text="Second"   Value=1>Second</asp:ListItem>
        </asp:DropDownList>


@Adding Items in Dropdown from c#
HTML Code:



C# Code added :  <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
C# Code:


protected void Page_Load(object sender, EventArgs e)
        {
            BindValue();
        }
        public void BindValue()
        {
            //DropDownList2.Items.Add(new ListItem("Zero"));  Binding only text
            DropDownList2.Items.Clear();
            DropDownList2.Items.Add(new ListItem("first", "1"));
            DropDownList2.Items.Add(new ListItem("Second", "2"));
        }


@OutPut
Bind data into dropdown from datasource

No comments:

Post a Comment