Monday, April 27, 2020

How add items in drop down list using c# code in asp.net


Create the web page and add the following code


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="dpTeams" runat="server"></asp:DropDownList>
        </div>
    </form>
</body>
</html>

Now add the following code into cs file of web page

using System;
using System.Web.UI.WebControls;

namespace Lab_1
{
    public partial class Add_Items_to_dropdown : System.Web.UI.Page
    {
        string[] teams = { "Team A", "Team B" , "Team C" , "Team D" };
        protected void Page_Load(object sender, EventArgs e)
        {
            setItemsToDropDown();
        }

        private void setItemsToDropDown()
        {
            dpTeams.Items.Clear();
            dpTeams.Items.Add(new ListItem(" - Select team - ", "0"));
            foreach(string team in teams)
            {
                dpTeams.Items.Add(new ListItem(team, team));
            }
        }
    }
}


Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...