Thursday, March 26, 2009

How To Create Multi Column Dropdownlist

In this post i will show how to create multi column dropdown list using asp.net .In your server side code, use the \u00A0 character as your padding character. Create calculated columns in your data table to set as the text field for the dropdownlist.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiCoulmn.aspx.cs" Inherits="MultiCoulmn" %>

<!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>
     <asp:DropDownList ID="ddlUser" runat="server">
     </asp:DropDownList>
 </div>
 </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MultiCoulmn : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       List<Friend> friends = GetFriends();
       foreach (Friend f in friends)
       {

           string text = string.Format("{0}|{1}", f.Name.PadRight(10, '\u00A0'), f.Description.PadRight(10,'\u00A0'));
           ddlUser.Items.Add(new ListItem(text, f.Id.ToString()));

       }
       ddlUser.DataBind();


   }
   public List<Friend> GetFriends()
   {

       List<Friend> users = new List<Friend>();
       users.Add(new Friend("Xyz", "Coder"));
       users.Add(new Friend("Abc", "Writer"));
       users.Add(new Friend("Charles", "Poet"));
       return users;


   }
}
public class Friend
{

   public Friend(string name, string description)
   {

       _name = name;

       _description = description;

       _id = Guid.NewGuid().ToString();

   }



   private string _id;
   public string Id
   {

       get { return _id; }

       set { _id = value; }

   }

   private string _name;
   public string Name
   {

       get { return _name; }

       set { _name = value; }

   }
   private string _description;
   public string Description
   {

       get { return _description; }

       set { _description = value; }

   }
}

5 comments :

  1. thanks Santosh, what is

    '\u00A0'


    ?

    todd at sayslaw.com

    ReplyDelete
  2. Hi
    it is used for "Non breaking space"

    ReplyDelete
  3. This one also can...

    For C #

    ddlCostCode.DataSource = dtCostCode();
    ddlCostCode.DataTextField = "IDesc";
    ddlCostCode.DataValueField = "ID";
    ddlCostCode.DataBind();
    ddlCostCode.Items.Insert(0, new ListItem("[Select Cost Code]", "0"));

    For Query

    SELECT ID, [Description], (ID + ' - ' + Description) as IDesc
    FROM tbl_CostCode

    ReplyDelete
  4. Been trying to solve this problem for hours! just wanted to sat thank you!

    ReplyDelete