Retrieving ComboBox items with a populated DataSource

Note that there is a ComboBox that is populated through its DataSource property. Each item in a ComboBox is a custom object, and a ComboBox is installed with DisplayMemberand 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 elements as a string that will be displayed in the user interface. Think that I do not know the type of each element in the ComboBox ( CustomItemunknown to me)

Is it possible?

+3
source share
4 answers

Binding:

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

Receive item:

CustomItem ci = ComboBox1.SelectedValue as CustomItem;

edit: If all you want is a list of all displayed combobox values

List<String> displayedValues = new List<String>();
foreach (CustomItem ci in comboBox1.Items)
    displayedValues.Add(ci.Value);
+3

, ICustomFormatter, .

interface ICustomFormatter
{
   public string ToString();
}

ToString().

EDIT: Decorator .

+2

You should be able to get the value of ValueMember and DisplayMember through reflection. But polling combobox might be a little easier. The following will work, but maybe you want to surround it with SuspendUpdate or something like that.

string s = string.Empty;
int n = comboBox1.Items.Count;

for (int i = 0; i < n; i++)
{
    comboBox1.SelectedIndex = i;
    s = s + ';' + comboBox1.Text; // not SelectedText;
}
+2
source

Although a little more computationally expensive, Reflection can 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;
    }
+2
source

Source: https://habr.com/ru/post/1708398/


All Articles