How to bind dropdown using dictioanry

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div style="padding:100px">
        <h3>Bind Dropdown using dictionary</h3>
       <strong> Select City  :</strong><asp:DropDownList ID="ddlCity" runat="server" Width="200px"></asp:DropDownList>
        </div>
    </div>
    </form>
</body>
</html>

Code-behind

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;


namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                BindCity();
        }

        private void BindCity()
        {
            Dictionary<string, string> dicCity = new Dictionary<string, string>();
            //Add city to dictionary
            dicCity.Add("1", "New Delhi");
            dicCity.Add("2", "Mumbai");
            dicCity.Add("3", "Banglore");
            dicCity.Add("4", "Pune");
            dicCity.Add("5", "Nagpur");
            dicCity.Add("6", "Jaipur");
            dicCity.Add("7", "Chandighar");

            ddlCity.DataSource = dicCity;
            ddlCity.DataValueField = "key";
            ddlCity.DataTextField = "Value";
            ddlCity.DataBind();

        }
    }
}
Ebook Download
View all
Learn
View all