Karim O.
Karim O.

Reputation: 1365

Convert list of type object into string to display on listbox

I have a list of type object like so: List <Sentence> sentences = new List<Sentence>();

and the list contains various strings/sentences that I want to display on a listbox, however, everytime I try to display that list, the listbox displays (Collection)

What I have: listBox1.Items.Add(sentences);

Is there a way to convert that object to a string so that the text/sentence in the list is readable on the listbox?

The contents of a sentence structure is only a string variable.

enter image description here

Upvotes: 0

Views: 3634

Answers (5)

Tal Jerome
Tal Jerome

Reputation: 676

It seems you are adding a list of Sentences into the listbox. I'm not sure what you expect should happen... My guess is you are trying to add each Sentence in the list to the listbox therefor you should use the AddRange option as described in the other answers. Anyways, if you do use AddRange you can then use the "DisplayMember" property of the listbox to display the property holding the Text in the Sentence class.

    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.DisplayMember = "Text";
        listBox1.Items.Add(new Sentence { Text = "abc" });
        listBox1.Items.Add(new Sentence { Text = "abc1" });
        listBox1.Items.Add(new Sentence { Text = "abc2" });
    }

    public class Sentence
    {
        public string Text { get; set; }
    }

Upvotes: 0

bash.d
bash.d

Reputation: 13207

You are adding the collection item itself (i.e. sentences) to the ListBox-control. You'll Need to override the ToString()-method in Sentence-class to return the textvalue of the sentence. Then use a foreach-loop and add your sentences to the ListBox like:

foreach(Sentence sen in sentences){
  ListBox1.Items.Add(sen.ToString());
}

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460028

You have to override ToString:

public class Sentence
{
    public string Text{ get; set; }

    public override string ToString()
    {
        return this.Text;
    }
}

Note that Formatting should be disabled:

listBox1.FormattingEnabled = false;

as mentioned here.

Another way is using Linq and AddRange:

listBox1.Items.AddRange(sentences.Select(s => s.Text).ToArray());

(assuming your Sentence class has a property Text)

Upvotes: 0

Eric J.
Eric J.

Reputation: 150108

If you wish to show something representative of an instance of Sentence in the listbox, override ToString()

public class Sentence
{
    public override string ToString()
    {
        //return something meaningful here.
    }

    // Rest of the implementation of Sentence
}

Upvotes: 4

Haedrian
Haedrian

Reputation: 4328

You are seeing a string. Specifically you're seeing the .toString() of that object.

You want to pass the content of the collection there - try .AddRange() instead.

Upvotes: 0

Related Questions