Search code examples
asp.netdrop-down-menudatatextfield

How to concatenate values in dropdownlist in asp.net


recently while working on the dropdownlist, i came accross a strange issue, i am binding a datatable to dropdownlist, now my datatable contains 3 columns, (Name,Id,Count), in DataTextField i want to concatenate Name and count like below.

DropDownlist.DataTextField = "Name (Count)";

but i am unable to do above thing, is there any other way i can achieve the above aim, i know the work around, using loop and concatenating in the

DropDownlist.Items.Add();

but i want to know whether i can do using DataTextField.


Solution

  • You can if you can create a custom data field in your data source and do the concatenation in there. For instance, something like so (you may have to some casting or converting, but hopefully you get the idea):

    SELECT
    Name,
    Count,
    Id,
    Name + ' (' + Count + ')' AS DataField
    FROM
    TABLE
    

    Then set

    DropDownlist.DataTextField = "DataField";