Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hi all
i have a dropdown list that give 2 column of a table with a datasource
table: Room
columns : Room_Code,Room_Capacity
i need to display something like this
Room : 20 Capacity : 4
Room : 21 Capacity : 2
.
.
.
in the drop down list
what can i do?

What I have tried:

i search in this site and find someways but not working at all
i read this Multiple Columns DropDown for ASP.NET[^]
but its vb.net i need C# code
Posted
Updated 25-Oct-17 7:49am
v3
Comments
F-ES Sitecore 25-Oct-17 9:19am    
This is a very common requirement, if you keep googling I'm sure you'll find something you can use.
Member 13019612 25-Oct-17 9:30am    
i dont know bro will try

1 solution

Hi,


To display the two data from the datatable columns in your dropdownlist, I suggest that you format the data before bind it. Use linq for this.
This is the easiest way.

Here is an example of this suggestion.

HTML
ASP.NET
<form id="form1" runat="server">
<div>
     <asp:DropDownList ID="ddl_room" runat="server">
    </asp:DropDownList>
</div>
</form>


CODE BEHIND
C#
private DataTable SelectData()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Room_Code", typeof(string));
    dt.Columns.Add("Room_Capacity", typeof(string));

    DataRow dr = dt.NewRow();
    dr["Room_Code"] = "20";
    dr["Room_Capacity"] = "4";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr["Room_Code"] = "21";
    dr["Room_Capacity"] = "2";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr["Room_Code"] = "22";
    dr["Room_Capacity"] = "1";
    dt.Rows.Add(dr);

    dr = dt.NewRow();
    dr["Room_Code"] = "1";
    dr["Room_Capacity"] = "10";
    dt.Rows.Add(dr);
 
    return dt;

}

private void CreateDataSourceFillDropList(DataTable dt)
{
    var datasource = from x in dt.AsEnumerable()
            select new {
                Code = x.Field<string>("Room_Code")
                ,DisplayField = String.Format("Room: {0} Capacity: {1}", x.Field<string>("Room_Code").PadLeft(2, '0'), x.Field<string>("Room_Capacity").PadLeft(2, '0'))
            };

    this.ddl_room.DataTextField = "DisplayField";
    this.ddl_room.DataValueField = "Code";
    this.ddl_room.DataSource = datasource;
    this.ddl_room.DataBind();   
}
        
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.CreateDataSourceFillDropList(this.SelectData());
                
    }
}
 
Share this answer
 
v3
Comments
Karthik_Mahalingam 26-Oct-17 3:56am    
5

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900