在尝试将XML绑定到Combobox数据源时,我收到错误“ 复杂数据绑定接受IList或IListSource作为数据源。 ”
XDocument obj = XDocument.Load("Managers.xml");
comboBox1.DisplayMember = "ManagerDesig";
comboBox1.ValueMember = "ManagerID";
comboBox1.DataSource = obj.Descendants("manager").Select(x => new
{
ManagerDesig = x.Attribute("desig").Value,
ManagerID = x.Attribute("id").Value
});
Managers.xml
<managers>
<manager id="123" desig="CEO" />
<manager id="234" desig="CFO" />
<manager id="456" desig="CIO" />
</managers>
请帮忙
答案 0 :(得分:3)
尝试:
comboBox1.DataSource = obj.Descendants("manager").Select(x => new
{
ManagerDesig = x.Attribute("name").Value,
ManagerID = x.Attribute("id").Value
})
.ToList();//convert to list
答案 1 :(得分:1)
首先,您的示例中存在拼写错误:您正在检索“name”属性,而只定义了“id”和“desig”属性。
其次,使用ToList扩展方法,如下所示:
comboBox1.DataSource = obj.Descendants("manager").Select(x => new
{
ManagerDesig = x.Attribute("name").Value,
ManagerID = x.Attribute("id").Value
}).ToList();