3

我不确定这是否可行,但是我有一个复杂类型的字典,我想将它绑定到 RadioButtonList/CheckBoxList 控件:

public class ComplexType
{
   public String Name { get; set; }
   public String FormattedName { get; set; }
   public String Description { get; set; }
}
var listOfMyTypes = new Dictionary<int, ComplexType>();

var myType = new ComplexType { Name = "Name", Description = "Description", FormattedName = "Name|Description" };
var myType1 = new ComplexType { Name = "Name2", Description = "Description2", FormattedName = "Name|Description2" };


listOfMyTypes.Add(1, myType);
listOfMyTypes.Add(2, myType1);

m_dropDownlist.DataTextField = "Value"; //What do I put here to render "Name"
m_dropDownlist.DataValueField = "Key";
m_dropDownlist.DataSource = listOfMyTypes;
m_dropDownlist.DataBind();
4

3 回答 3

2

尝试Dictionary.Values像这样绑定到:

m_dropDownlist.DataTextField = "Name"
m_dropDownlist.DataValueField = "Description";
m_dropDownlist.DataSource = listOfMyTypes.Values;
m_dropDownlist.DataBind();
于 2012-06-30T13:50:49.427 回答
1

您将 TextField 设置为要显示的属性。您将 ValueField 设置为要发布的属性。最后,绑定到字典的值。我正在寻找 DropDownList 的“模板”版本,但没有找到。所以,如果你需要字典的钥匙,你可能不得不用艰难的方式来做——循环/添加。

m_dropDownlist.DataTextField = "FormattedName"; //What do I put here to render "Name" 
m_dropDownlist.DataValueField = "Name"; 
m_dropDownlist.DataSource = listOfMyTypes.Values; 
m_dropDownlist.DataBind(); 

我确实找到了另一种方法。您可以在您的课程中覆盖“ToString()”:

public class ComplexType      
{      
   public String Name { get; set; }      
   public String FormattedName { get; set; }      
   public String Description { get; set; } 
   public override string ToString()
   {
      return this.Name;
   }     
}  

然后正常绑定:

m_dropDownlist.DataTextField = "Value"; //What do I put here to render "Name" 
m_dropDownlist.DataValueField = "Key"; 
m_dropDownlist.DataSource = listOfMyTypes; 
m_dropDownlist.DataBind(); 
于 2012-06-30T13:47:25.477 回答
0

你可以写

m_dropDownlist.DataTextField = "Value.Name";

于 2013-01-25T14:34:20.140 回答