Convert list of type object into string to display on listbox

走远了吗. 提交于 2019-12-13 03:59:31

问题


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.


回答1:


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
}



回答2:


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



回答3:


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.




回答4:


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)




回答5:


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; }
    }


来源:https://stackoverflow.com/questions/15466310/convert-list-of-type-object-into-string-to-display-on-listbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!