Vincular diccionario de tipo complejo a RadioButtonList

I'm not sure if this is possible but, I have a dictionary of a complex type and I want to bind it to RadioButtonList/CheckBoxList control:

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

preguntado el 30 de junio de 12 a las 14:06

3 Respuestas

Intenta enlazar a Dictionary.Values en lugar de esto:

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

Respondido el 30 de junio de 12 a las 14:06

This is exactly what I was looking for, just needed a second pair of eyes. Thanks! - stefano d

You set the TextField to the property you want to display. You set the ValueField to the property you want posted. Finally, bind to the Values of the Dictionary. I'm looking for a "template" version of the DropDownList, but not finding one. So, if you need the Key of the Dictonary, you may have to do it the hard way - loop / add.

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

I did find another way. You can override "ToString()" in your class:

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;
   }     
}  

Then bind normally:

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

Respondido el 30 de junio de 12 a las 15:06

Puedes escribir

m_dropDownlist.DataTextField = "Value.Name";

Respondido el 25 de enero de 13 a las 14:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.