[英]How to display an object property in a drop down list in VB.Net/C# and ASP.NET
我正在使用VB.Net和ASP.net,但也欢迎使用C#代码。
我有一个客户端列表,客户端属性是:
-clientid
-全名
样本数据:
-clientid:1
全名:约翰·宾德
-clientid:2
姓氏:Leah Brown
我有一个协议“ lstAgreements”列表,它们的属性是:
-AgreementID
-clientid
-日期
样本数据:
AGREEMENTID:5
客户端ID:2
日期:16年12月30日
AGREEMENTID:7
客户端ID:1
日期:16年12月29日
“客户”和“协议”是具有现有关系的实体类:一个客户可以拥有许多协议。
我可以通过以下方式检索所有协议:
Dim lstAgreements As List(Of Agreement) =GetAllAgreements()
协议类具有获取客户端对象的属性:
lstAgreements(0).ClientObject.FullName
然后,我可以使用“ lstAgreements”填充下拉列表
myDropDownList.DataSource = lstAgreements
myDropDownList.DataValueField = "AgreementID"
myDropDownList.DataTextField = "ClientID"
myDropDownList.DataBind()
我的问题是,如何在下拉列表中显示“ ClientFullName”而不是“ ClientID”?
我正在尝试此代码,但它不起作用:
myDropDownList.DataSource = lstAgreements
myDropDownList.DataValueField = "AgreementID"
myDropDownList.DataTextField = "ClientObject.FullName"
myDropDownList.DataBind()
我注意到在DataList控件中使用“ ClientObject.FullName”可以正常工作,但在下拉列表中则不能。
有什么建议吗?
提前致谢
您可以遍历第一协议,而不是使用数据源/数据绑定并自己创建列表项?
就像是
foreach (Agreement a in lstAgreements)
{
myDropDownList.Items.Add(new ListItem(a.ClientObject.FullName, a.AgreementId))
}
或使用linq从客户端列表中设置您的全名(如果您没有全名方法来按协议返回全名)。
您为什么不像这样使用它:
myDropDownList.DataTextField = "FullName";
更新 :
显然,“协议”不包含名称为“ FullName”的属性。 它具有-AgreementID -ClientID -Date属性。
我建议使用Linq从多个列表(C#)中检索所需的数据:
public class CustomList
{
public string FullName { get; set; }
public int AgreementID{ get; set; }
}
var Custom = from i in listofClients
from j in listofAgreements
Where i.ClientID == j.ClientID
select new CustomList{
FullName = i.FullName ,
AgreementID = j.AgreementID
}.ToList();
现在您可以使用Custom
将其绑定到您的DropDownList
:
myDropDownList.DataSource = Custom ;
myDropDownList.DataValueField = "AgreementID";
myDropDownList.DataTextField = "FullName";
myDropDownList.DataBind();
根据您的控件(尽管我认为这是默认行为),您也可以通过覆盖对象的ToString()方法来执行此操作。 通常,这将给出其类型的字符串表示形式,但是如果将返回值更改为所需的属性,则它将是ToString()的值。 如果然后绑定到IEnumerable lstAgreements之类的东西,则甚至不必进行属性搜索。 dropdownlist项目的值将是对象,文本将是其ToString()输出。
伪:
prop int AgreementID
prop int ClientID
prop DateTime Date
prop ClientObject CO;
public IEnumerable<Agreement> GetAllAgreements()...
public override string ToString()
{
return this.CO.FullName;
}
-----------
mydropdown.DataSource = GetAllAgreements(); Databind();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.