[英]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.