使用带分隔符的字符串将项目添加到列表框 [英] Adding items to a Listbox from a string with delimiters
问题描述
如何像使用,"作为分隔符的字符串那样将项目添加到ListBox.就像假设我要向ListBox添加名字.如何从"rupa,anitha,latha,rani"之类的字符串中添加这些项目?
有人可以帮我吗?
在此先感谢!
ListBox lst = new ListBox(); lst.Items.Add(new ListItem("rupa")); lst.Items.Add(new ListItem("anitha")); lst.Items.Add(new ListItem("latha")); lst.Items.Add(new ListItem("rani"));
那就是你要找的东西吗?
好了,正如曼弗雷德(Manfred)所建议的那样,我可以像
那样修改答案
string str = "hiren,manfred,you,me,all,cp"; string[] items = str.split('',''); for(int i=0;i<items.length;i++)> { lst.add(new ListItem(string[i])); }
尝试一下:
public ListBox AddItemsToListBoxFromString(ListBox lb, String strItems,字符 []分隔符) { 字符串 [] items = strItems.Split(separators); foreach (字符串项目 in 项目中) { lb.Items.Add(item.Trim()); } 返回 lb; }
来自文件背后代码的典型调用可能如下所示:
... AddItemsToListBoxFromString(listBox1," ,字符 [] { ,'}); ...
希望对您有帮助!
最好的问候,
曼弗雷德(Manfred)
形式上,已经有正确的答案.
我会建议对所有显示的代码进行小幅改进:
字符串 []项目= source.Split( 新 字符 [] {' ',' ,'}, StringSplitOptions.RemoveEmptyEntries);
How can I add items to ListBox like from a string using "," as a delimiter. Like suppose I want to add first names to a ListBox. How can I add these items from a string like "rupa,anitha,latha,rani"?
Can any body help me?
Thanks in advance!解决方案ListBox lst = new ListBox(); lst.Items.Add(new ListItem("rupa")); lst.Items.Add(new ListItem("anitha")); lst.Items.Add(new ListItem("latha")); lst.Items.Add(new ListItem("rani"));
That is what you looking for ?
Ok now as manfred suggested I can revise my answer like
string str = "hiren,manfred,you,me,all,cp"; string[] items = str.split('',''); for(int i=0;i<items.length;i++)> { lst.add(new ListItem(string[i])); }
Try this:
public ListBox AddItemsToListBoxFromString(ListBox lb, String strItems, char[] separators) { String[] items = strItems.Split(separators); foreach(String item in items) { lb.Items.Add(item.Trim()); } return lb; }
A typical call from a code behind file might look like this:
... AddItemsToListBoxFromString(listBox1, "rupa,anitha,latha,rani", new char[] { ',' }); ...
Hope this helps you!
Best Regards,
Manfred
Formally, there are correct answers already.
I would add advice a minor improvement to all the presented codes:
string[] items = source.Split( new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
It allows for more relaxed human-readable requirements for the format of the input.
这篇关于使用带分隔符的字符串将项目添加到列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!