Click here to Skip to main content
Click here to Skip to main content
Go to top

Binding ASP.NET DropDownList to data structures

, 15 Dec 2011
Rate this:
Please Sign up or sign in to vote.
DropDownList Data Binding to Array (1D/2D), Enum and Dictionary objects in .NET
Data Binding is the process that establishes a connection between the application UI and business logic. This post describes the dynamic Data Binding of DropDownList to various data structures available in .NET Framework (2.0/3.5/4.0), namely: single- and two-dimensional Array, Enum and Dictionary object.
 
Data Binding essentially could be done in two alternative ways: by using either iterative technique, i.e., looping through the data structure object and adding items to DropDownList, or by using the DataSource/DataBind() property/method of the DropDownList. The following code snippets written in C#/ASP.NET implement both techniques, pertinent to data structures mentioned above (for demo purposes encapsulated in Default.aspx file with corresponding code-behind Default.aspx.cs file)

Listing 1. Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>Binding DropDownList | ASP.NET</title>
</head>
<body>
    <form id="form1"  runat="server">
    <div>
        <asp:DropDownList ID="ddl2DictionaryDataBind" runat="server" />
        <asp:DropDownList ID="ddl2DictionaryBindValues" runat="server" />
        <asp:DropDownList ID="ddl2DictionaryLoop" runat="server" />
        <asp:DropDownList ID="ddl2EnumBindValues" runat="server" />
        <asp:DropDownList ID="ddl2EnumLoop" runat="server" />
        <asp:DropDownList ID="ddl2Array" runat="server" />
        <asp:DropDownList ID="ddl2Array2d" runat="server" />
    </div>
    </form>
</body>
</html>
 

Listing 2. Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Data;
using System.Linq; // this is only needed for Method 1b

public partial class _Default : System.Web.UI.Page
{
    // sample 1d array containing string items: countries in North America
    string[] arrCountries = { "United States of America", "Canada", "Mexico" };
 
    // sample 2d array containing string items: countries in North America and corresponding Country codes (ISO 3166)
    string[,] arrCountries2d = { {"United States of America", "US"}, {"Canada", "CA"}, {"Mexico", "MX"} };
 
    // sample enum containing Country codes in North America
    // with numeric representation (ISO 3166)
    enum enumCountries { US=840, CA=124, MX=484 };
    
    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack)  {
            // create sample dictionary object: country list in North America
            Dictionary<string,> dictCountries = new Dictionary<string,>();
            dictCountries.Add("US", "United States of America");
            dictCountries.Add("CA", "Canada");
            dictCountries.Add("MX", "Mexico");
 
            // Method 1a: Data Binding DropDownList to Dictionary using DataSource and DataBind()
            ddl2DictionaryDataBind.DataSource = dictCountries;
            ddl2DictionaryDataBind.DataTextField = "Value";
            ddl2DictionaryDataBind.DataValueField = "Key";
            ddl2DictionaryDataBind.DataBind();
            ddl2DictionaryDataBind.ToolTip = "Data Bind to Dictionary using Value/Key";
            
            // Method 1b. Data Binding DropDownList to Dictionary (either Keys or Values)
            // using DataSource property of the DropDownList object. This method will
            // render the <select> HTML element with option values and inner HTML
            // both corresponding to Dictionary Values (it could be bound to Keys instead)
            // note: this method requires System.Linq reference
            ddl2DictionaryBindValues.DataSource = dictCountries.Values.ToArray();
            ddl2DictionaryBindValues.DataBind();
            ddl2DictionaryBindValues.ToolTip = "Data Bind to Dictionary using only Values";
            
            // Method 1c. Data Binding DropDownList to Dictionary using iterations:
            // looping through the dictionary items and adding them to the DropDownList
            // this method will render the <select> HTML element with option values 
            // corresponding to Dictionary Keys and inner HTML corresponding to Values
            // note: if Dictionary contains data types other than String (for example, Dictionary<int,>)
            // then add the ToString() conversion to that data type
            ddl2DictionaryLoop.ToolTip = "Bind to Dictionary (Key/Values) using iteration";
            foreach (KeyValuePair<string,> _dictItem in dictCountries)
            {
                ddl2DictionaryLoop.Items.Add(new ListItem(_dictItem.Value, _dictItem.Key));
            }
 
            // Method 2a. Data Binding DropDownList to Enum using DataSource/DataBind()
            ddl2EnumBindValues.ToolTip = "Data Bind to Enum, Values only";
            ddl2EnumBindValues.DataSource = Enum.GetNames(typeof(enumCountries));
            ddl2EnumBindValues.DataBind();
 
            // Method 2b. Data Binding DropDownList to Enum, alternative method using iteration
            ddl2EnumLoop.ToolTip = "Bind to Enum (Key/Values) using iteration";
            foreach (enumCountries co in Enum.GetValues(typeof(enumCountries)))
            {
                string _val = co.ToString();
                string _key = ((Int32)Enum.Parse(typeof(enumCountries), _val)).ToString();
                ddl2EnumLoop.Items.Add(new ListItem(_val, _key));
            }
    
            // Method 3a. Data Binding DropDownList to 1D-array of strings (countries in North America)
            ddl2Array.ToolTip = "Data Bind to 1d array";
            ddl2Array.DataSource = arrCountries;
            ddl2Array.DataBind();
 
            // Method 3b. Data Binding DropDownList to 2D-array of strings (countries in North America)
            ddl2Array2d.ToolTip = "Bind to 2d array";
            for (int i = 0; i < arrCountries2d.GetLength(0); i++)
            {
                ddl2Array2d.Items.Add(new ListItem(arrCountries2d[i, 0], arrCountries2d[i, 1]));
            }
        }
    }
}
// ***************************************************************
 
For more details on this topic, refer to the reference [1].

Reference

  1. A.Bell, Binding DropDownList to various data structures in Microsoft ASP.NET[^]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DrABELL
President Infosoft International Inc
United States United States
Dr. A. Bell has 20+ years of Software and Electrical Engineering experience. He is Win/Web veteran, published 200+ articles and authored 37 inventions, currently focused on: Windows 7/8, HTML5, CSS3, jQuery, SQL, .NET, ASP.NET, WPF, C#, Speech Technology and Mobile apps. He's been among recent App submission winners (The Windows 8* & Ultrabook™ App Innovation Contest 2012). Sample pubs:
  1. Edumatter M12: School Math Calculators and Equation Solvers (contest winner)
  2. Engineering Calculator VOLTA-2013 (contest winner)
  3. HTML5 Best Practices: Table formatting via CSS3
  4. Edumatter-M12 for Windows, app overview
  5. Engineering Calculator VOLTA-814D
  6. CoolPhone: phone numbers-to-text converter
  7. SQL generates large data sequence
  8. Aggregate Product function extends SQL
  9. Top-50 Digital Cameras
  10. WebTV Project: Embedded YouTube Player (Goog #1 YouTube API for ASP.NET)
Dr. Bell is personally credited for 10+ Enterprise level projects (Finance/Investment, Engineering, Edu) w/total code base exceeding 250k lines; doing consulting in NYC for 20 yrs.
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web02 | 2.8.140921.1 | Last Updated 15 Dec 2011
Article Copyright 2011 by DrABELL
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid