简体   繁体   English

如何用字符串分隔的逗号填充 C# 列表框

[英]How to populated C# listbox with string separated comma

I have a string that separated by comma like this:我有一个用逗号分隔的字符串,如下所示:

"test1,test2,test3"

and i want to convert those string to list with folowing code:我想使用以下代码将这些字符串转换为列表:

    private void convertToList()
    {
        try{
            List<string> myList = occ.Split(',').ToList();
            listBox1.Items.Add(myList);
        }catch(Exception e){
            MessageBox.Show(e.Message);
        }
        
    }

I think that code will convert the string into a list and add it into a Listbox, instead, it shows only "collection"(yes only show the word "collection", nothing more) not the actual list.我认为该代码会将字符串转换为列表并将其添加到列表框中,相反,它仅显示“集合”(是的,仅显示“集合”一词,仅此而已)而不是实际列表。 why that's happened?为什么会这样? can you tell me what's the right code?你能告诉我什么是正确的代码吗?

Well, Add adds a single item which is a List<string> in your case.好吧,在您的情况下, Add添加了一个List<string>项目。 What should ListBox show for this? ListBox应该为此显示什么? Collection seems to be a good enough solution. Collection似乎是一个足够好的解决方案。 If you want to add entire collection in one go , try AddRange :如果您想在一个 go中添加整个集合,请尝试AddRange

listBox1.Items.AddRange(occ.Split(','));

If you insist on Add , you have to loop in order to Add each item of the collection:如果您坚持Add ,则必须循环Add集合的每个item

// To stop unwanted redrawing after each item addition
listBox1.BeginUpdate();

try {
  foreach (var item in occ.Split(','))
    listBox1.Items.Add(item);
}
finally {
  listBox1.EndUpdate();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM