Display specified text for list items

I have a list containing custom objects. These objects have different properties and I have ~ 100 of them. I want to create a list of them in the list, but the list shows only

  MyNamespace.MyClass
  MyNamespace.MyClass
  MyNamespace.MyClass
  MyNamespace.MyClass
  ...

      

Is it possible for the list to display a specific value for each item? Let's say my objects have an ID string value. Is it possible to display the ID for each item without discarding other properties of other objects?

I am currently populating the list this way:

  lbox.Items.Clear();
  lbox.Items.AddRange(list.ToArray());

      

+3


source to share


4 answers


Set the DisplayMember

property of your class that you would like to see.



lbox.Items.Clear();
lbox.Items.AddRange(list.ToArray());

lbox.DisplayMember = "ID";  // ID is a public property in MyClass

      

+2


source


Let's assume MyClass looks like this:

public class MyClass
{
    public int Id { get; set; }
}

      

There are two options available.



  • You can use DataBinding for this.

    Set DisplayMember

    to the setting of your MyClass which you want to display

    lbox.DisplayMember = "Id";
    
          

    Set elements using a property of DataSource

    yourListBox

    lbox.DataSource = list.ToArray();
    
          

  • You can simply override the method of ToString

    your object MyClass

    and return the text you want to display.

    Override method of ToString

    your MyClass

    public class MyClass
    {
        public int Id { get; set; }
    
        public override string ToString()
        {
            return Id.ToString();
        }
    }
    
          

    Set the items the same way you mentioned

    lbox.Items.AddRange(list.ToArray());
    
          

Additional Information

+2


source


Try using Linq.

lbox.Items.AddRange(list.Select(x => x.ID).ToArray());

      

Where ID

is the property with the value you want to show.

You can also override ToString()

in the class.

+1


source


Without dropping the object, you can attach the object to the tag after.

list.ToList().ForEach(item => lbox.Items.Add(new ListItem(item.ID){Tag = item});

      

and then:

var myitem = ((ListItem)lbox.SelectedItem).Tag as MyClass;

      

+1


source







All Articles