How to concatenate values in dropdownlist in asp.net
recently while working on the dropdownlist, i cam开发者_运维知识库e 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.
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";
You can do like this.... i hope it will helps you .....i have added sample data to the datatable ,you can use your data,
DataTable table = new DataTable();
table.Columns.Add("id");
table.Columns.Add("name");
table.Columns.Add("count");
DataRow dr = table.NewRow();
dr["id"] = "1";
dr["name"] = "zhang";
dr["count"] = "6";
table.Rows.Add(dr);
DataRow[] rows = new DataRow[table.Rows.Count];
table.Rows.CopyTo(rows, 0);
var res = from row in rows
select new
{
id=row["id"].ToString (),
namewithcount = row["name"].ToString () +"(" row["count"].ToString ()+")";
};
DropDownList1.DataSource = res;
DropDownList1.DataTextField = "namewithcount";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
Ther is no way to do this in the way you are trying too because the datatextfield value requires the single name of the column. If you do not want to go about this using the .Add() method you could always recreate the datatable with another column and column name that contains the concatenated values of Name and count in your desired formatting, but it would be way better if your filling this datatable from your database to change your query to include this fourth column with the concatenated values. Otherwise the Add() methods sounds like your best bet ;)
Here is a link to some information for the DataTextField
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.datatextfield(VS.85).aspx
精彩评论