在下面的源代码中,我正在从users
集合中选择一个子集属性,并需要将其绑定到下拉列表:
var locationDepts = (from u in users select new { u.RcNumber, u.RcName }).Distinct().ToList();
if(!locationDepts.Count.Equals(0))
{
ddlRCListPerBuilding.DataSource = locationDepts;
ddlRCListPerBuilding.DataValueField = "RcNumber";
//Want to format display test "RCNumber - RcName"
ddlRCListPerBuilding.DataTextField = string.Format("{0} - {1}", locationDepts.RcNumber, locationDepts.RcName);
ddlRCListPerBuilding.DataBind();
}
我想将列表项显示文本格式化为匿名类型rcnumber和rcname的组合。如何访问匿名类型的属性以指示下拉列表项的文本格式?
最佳答案
可以在数据源中创建名为“combined”的新属性
var locationDepts = (from u in users
select new
{
u.RcNumber,
Combined = u.RcNumber + " - " + u.RcName
}).Distinct().ToList();
if(locationDepts.Count > 0)
{
ddlRCListPerBuilding.DataSource = locationDepts;
ddlRCListPerBuilding.DataValueField = "RcNumber";
ddlRCListPerBuilding.DataTextField = "Combined";
ddlRCListPerBuilding.DataBind();
}