将XML绑定到Combobox

时间:2011-01-18 07:20:47

标签: c# linq

在尝试将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>

请帮忙

2 个答案:

答案 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();