将复杂类型的字典绑定到RadioButtonList

时间:2012-06-30 13:44:32

标签: c# asp.net webforms

我不确定这是否可行但是,我有一个复杂类型的字典,我想将它绑定到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();

3 个答案:

答案 0 :(得分:1)

将TextField设置为要显示的属性。 您将ValueField设置为要发布的属性。 最后,绑定到Dictionary的值。我正在寻找DropDownList的“模板”版本,但没有找到。所以,如果你需要Dictonary的Key,你可能必须这么做 - 循环/添加。

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(); 

答案 1 :(得分:1)

尝试绑定到Dictionary.Values,而不是这样:

m_dropDownlist.DataTextField = "Name"
m_dropDownlist.DataValueField = "Description";
m_dropDownlist.DataSource = listOfMyTypes.Values;
m_dropDownlist.DataBind();

答案 2 :(得分:0)

你可以写

m_dropDownlist.DataTextField = "Value.Name";