Bind DropDownList using simple user defined method in ASP.Net

 ASP.Net     sbo     Updated on Nov 19, 2014     VIKRAM     1144   

Introduction:

In this article i will explain how to bind DropDownList using simple user defined method in ASP.Net.

Description:

In previous articles i explained How to clear items from DropDownList (or) Select in Java ScriptHow to clear items from DropDownList (or) Select in jQueryHow to get selected index from DropDownList (or) Select in Java ScriptHow to get selected index from DropDownList (or) Select in jQueryHow to get selected text/value from DropDownList (or) Select in Java ScriptHow to get selected text/value from DropDownList (or) Select in jQuery, and How to set DropDownList value based on text/value in Java Script, How to set DropDownList value based on text/value in jQuery, and Now i will explain how to bind DropDownList using simple user defined method in ASP.Net.

Objective:

  1. Bind DropDownList using simple user defined method in ASP.Net
  2. User defined method should accept collection (e.g: List<Employee> or List<User> or List<Role> etc)
  3. User defined method should accept DataTable as well

In this article i created a class called CommonUI.cs with FillDropDown method as shown below:

using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace ASPDemos
{ 
    public class CommonUI
    {
        /// <summary>
        /// Binds list to DropDownList control.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dropDownList"></param>
        /// <param name="list"></param>
        /// <param name="dataTextField"></param>
        /// <param name="dataValueField"></param>
        public static void FillDropDown<T>(DropDownList dropDownList, List<T> list, string dataTextField, string dataValueField)
        {
            if (list != null && list.Count > 0)
            {
                dropDownList.DataSource = list;
                dropDownList.DataTextField = dataTextField;
                dropDownList.DataValueField = dataValueField;
                dropDownList.DataBind();
            }
            dropDownList.Items.Insert(0, (new ListItem("Select", "-1")));
        }
    }
}

FillDropDown method accepts 4 parameters:

  1. dropDownList - DropDownList ID for which you are binding
  2. list - It may be List<Employee>, List<User>, List<Role>, etc.
  3. dataTextField - Gets or sets the field of the data source that provides the text content of the list items.
  4. dataValueField - Gets or sets the field of the data source that provides the value of each list item

Assume we have a class called Role.cs as shown below:

Role.cs:

using System;
using System.Collections.Generic;
namespace ASPDemos
{
    public class Role
    {
        public int RoleID { get; set; }
        public string RoleName { get; set; }

        /// <summary>
        /// Get list of User Roles.
        /// </summary>
        /// <returns>List</returns>
        public static List<Role> GetRoles()
        {
            var lstRole = new List<Role>{
                new Role { RoleID = 1, RoleName = "User" },
                new Role { RoleID = 2, RoleName = "Admin" },
                new Role { RoleID = 3, RoleName = "Super Admin" }
            };
            return lstRole;
        }
    }
}

Bind User Role list to DropDownList:

Now bind list of roles to DropDownList as shown below:

CommonUI.FillDropDown(ddlRole, Role.GetRoles(), "RoleName", "RoleID");

Here we are accessing FillDropDown method directly with CommonUI class name. Because it is static method. Role.GetRoles() method returns List<Role>.

Bind User Role DataTable to DropDownList:

Assume that we have a DataTable called dtRole. Now bind this data table to DropDownList as shown below:

CommonUI.FillDropDown(ddlRole, dtRole.Rows.Cast<DataRow>().ToList(), "RoleName", "RoleID");

Here dtRole.Rows.Cast<DataRow>().ToList() returns List<DataRow>.

DataTable requires System.Data namespace, .ToList() method requires System.Linq namespace.

Full Source Code:

DropDownListDemo.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DropDownListDemo.aspx.cs" Inherits="ASPDemos.DropDownListDemo" %>

<!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>Bind DropDownList using simple user defined method in ASP.Net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddlRole" runat="server"></asp:DropDownList>
    </div>
    </form>
</body>
</html>

DropDownListDemo.aspx.cs:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;

namespace ASPDemos
{
    public partial class DropDownListFillMethod : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CommonUI.FillDropDown(ddlRole, Role.GetRoles(), "RoleName", "RoleID");

                // Uncomment below code when you pass DataTable into FillDropDown method.
                //DataTable dtRole = new DataTable();
                //CommonUI.FillDropDown(ddlRole, dtRole.Rows.Cast<DataRow>().ToList(), "RoleName", "RoleID");
            }
        }
    }

    public class Role
    {
        public int RoleID { get; set; }
        public string RoleName { get; set; }

        /// <summary>
        /// Get list of User Roles.
        /// </summary>
        /// <returns>List</returns>
        public static List<Role> GetRoles()
        {
            var lstRole = new List<Role>{
                new Role { RoleID = 1, RoleName = "User" },
                new Role { RoleID = 2, RoleName = "Admin" },
                new Role { RoleID = 3, RoleName = "Super Admin" }
            };
            return lstRole;
        }
    }

    public class CommonUI
    {
        /// <summary>
        /// Binds list to DropDownList control.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dropDownList"></param>
        /// <param name="list"></param>
        /// <param name="DataTextField"></param>
        /// <param name="DataValueField"></param>
        public static void FillDropDown<T>(DropDownList dropDownList, List<T> list, string DataTextField, string DataValueField)
        {
            if (list != null && list.Count > 0)
            {
                dropDownList.DataSource = list;
                dropDownList.DataTextField = DataTextField;
                dropDownList.DataValueField = DataValueField;
                dropDownList.DataBind();
            }
            // Insert 'Select' option at '0' index.
            dropDownList.Items.Insert(0, (new ListItem("Select", "-1")));
        }
    }
}

Output:

  Related Articles
Set DropDownList value based on text/value in jQuery
Set DropDownList value based on text/value in Java Script
Get selected text/value from DropDownList (or) Select in jQuery
Get selected text/value from DropDownList (or) Select in Java Script
Get selected index from DropDownList (or) Select in jQuery
Get selected index from DropDownList (or) Select in Java Script
Clear items from DropDownList (or) Select in Java script
Clear items from DropDownList (or) Select in jQuery.
  Recent Articles
Set DropDownList value based on text/value in jQuery
Set DropDownList value based on text/value in Java Script
Get selected text/value from DropDownList (or) Select in jQuery
Get selected text/value from DropDownList (or) Select in Java Script
Get selected index from DropDownList (or) Select in jQuery
Get selected index from DropDownList (or) Select in Java Script
Clear items from DropDownList (or) Select in Java script
Clear items from DropDownList (or) Select in jQuery.