2012-06-30 81 views
2

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

回答

1

尝试结合Dictionary.Values,而不是像这样:

m_dropDownlist.DataTextField = "Name" 
m_dropDownlist.DataValueField = "Description"; 
m_dropDownlist.DataSource = listOfMyTypes.Values; 
m_dropDownlist.DataBind(); 
+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(); 
0

你可以写

m_dropDownlist.DataTextField = "Value.Name";