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.
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
}
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());
}
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.
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
)
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; }
}