Search code examples
c#listboxlistviewitem

C# ListBox displays wrong format when used with ListViewItem


This is my code to populate a ListBox named delBooks with a ListViewItem object and items .Text and .Tag properties.

ListViewItem item = new ListViewItem();
item.Text = "ss"; // Or whatever display text you need
item.Tag = "dd";
delBooks.Items.Add(item);

The output I see in the ListBox looks like this:

ListViewItem: {ss}

How can I correct this so it will display ss in the ListBox?


Solution

  • An object like ListViewItem does not exist for ListBox. This is one of the reasons that the ListBox control was superseded by the ListView control. In order to get ListViewItem like functionality out of a ListBox control you must implement your own object

    class ListBoxItem
    {
        public string Text { get; set; }
        public string Tag { get; set; }
    
        public ListBoxItem(string text, string tag)
        {
            this.Text = text;
            this.Tag = tag;
        }
    }
    

    To populate the ListBox with your custom object simply do:

    listbox.DisplayMember = "Text";
    listbox.Items.Add(new ListBoxItem("ss", "dd"));
    

    Where the .DisplayMember property of ListBox is the name of the property of your custom object that is to be displayed in the ListBox to the user.

    If you need to access your custom objects values based on your ListBox item collection you can do a simple cast to retrieve the these values:

    MessageBox.Show( ((ListBoxItem)listbox.Items[0]).Tag) );
    

    Where the .Tag property is the value "dd" that we set earlier

    PS: If you're a stickler for design like I am this method will also work with a struct

    EDIT: If you are truly dead set on using ListViewItem you technically can just by setting the .DisplayMember to (in your case) the .Text property of the ListViewItem object