views:

391

answers:

3

Consider that there is a ComboBox which is populated through its DataSource property. Each item in the ComboBox is a custom object and the ComboBox is set with a DisplayMember and ValueMember.

IList<CustomItem> aItems = new List<CustomItem>();
//CustomItem has Id and Value and is filled through its constructor
aItems.Add(1, "foo"); 
aItems.Add(2, "bar");

myComboBox.DataSource = aItems;

Now the problem is that, I want to read the items as string that will be rendered in the UI. Consider that I don't know the type of each item in the ComboBox (CustomItem is unknown to me)

Is this possible ?

+1  A: 

Binding:

ComboBox1.DataSource = aItems;
ComboBox1.DisplayMember = "Value";

Getting the item:

CustomItem ci = ComboBox1.SelectedValue as CustomItem;

edit: If all that you want to get is a list of all of the display values of the combobox

List<String> displayedValues = new List<String>();
foreach (CustomItem ci in comboBox1.Items)
    displayedValues.Add(ci.Value);
SnOrfus
Its about the items and not the selected one.
+1  A: 

Create an Interface, say ICustomFormatter, and have those custom objects implement it.

interface ICustomFormatter
{
   public string ToString();
}

Then call the ToString() method.

EDIT: link to Decorator pattern.

Mitch Wheat
Is this the only way ?? I cannot modify the CustomObject class. Is there any other way ???
Create a decorator around those custom objects...
Mitch Wheat
Object defines a ToString() method. If you wanted to do this, you'd just override that instead of implementing a new interface.
SnOrfus
Sounds like a better solution. I will try to modify the CustomItem, if I don't have permission, will go on with the 'decorator' stuff
+1  A: 

Although slightly more computationally expensive, Reflection could do what you want:

using System.Reflection;    
private string GetPropertyFromObject(string propertyName, object obj)
    {
        PropertyInfo pi = obj.GetType().GetProperty(propertyName);
        if(pi != null)
        {
         object value = pi.GetValue(obj, null);
         if(value != null)
         {
          return value.ToString();
         }
        }
        //return empty string, null, or throw error
        return string.Empty;
    }
Zack