Adding XML elements to ListBox

大城市里の小女人 提交于 2019-12-25 05:06:07

问题


I don't know how to convert the type for name so that each element in it can be added to my ListBox. If someone could help that would be much appreciated.

XDocument doc = XDocument.Load(workingDir + @"\Moduleslist.xml");

var names = doc.Root.Descendants("Module").Elements("Name").Select(b => b.Value);

listBox1.Items.AddRange(names);

I'm getting an error on AddRange(names) saying invalid arguments


回答1:


names is IEnumerable<String> and listBox.Items.AddRange is expecting an object array and there is no implicit cast between them.

A quick solution would be to:

listBox1.Items.AddRange(names.ToArray());

or

foreach (var item in names)
{
    listBox1.Items.Add(item);
}



回答2:


Try this code instead of your last line of code:

listBox1.DataSource = names;
this.listBox1.DisplayMember = YOURDISPLAYMEMBER;
this.listBox1.ValueMember = YOURVALUEMEMBER;



回答3:


maybe:

listBox1.Items.AddRange(doc.Root.Descendants("Module").Elements("Name").Select(b => b.Value).ToArray());


来源:https://stackoverflow.com/questions/9955199/adding-xml-elements-to-listbox

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