如何使用XLinq读取XML并将其绑定到组合框?

时间:2011-06-09 19:47:55

标签: c# xml winforms linq-to-xml

您好我正在尝试使用XLinq读取XML文件并将值绑定到组合框: -

 XDocument xmlDoc = XDocument.Load("abc.xml");
 var res = from c in xmlDoc.Element("Clients").Descendants("Client")
           select c;

 cmb1.BindingContext = new BindingContext();
 cmb1.DataSource = res;
 cmb1.DisplayMember = "Name";
 cmb1.ValueMember = "ID";

我的XMl结构是这样的: -

<Clients>
    <Client>
        <ID>-1</ID>
        <Name>--Select--</Name>
    </Client>
    <Client>
        <ID>1</ID>
        <Name>A</Name>
    </Client>
    <Client>
        <ID>2</ID>
        <Name>B</Name>
    </Client>
    <Client>
        <ID>3</ID>
        <Name>C</Name>
    </Client>
    <Client>
        <ID>4</ID>
        <Name>D</Name>
    </Client>
</Clients>

但不知怎的,我得到了错误。请求帮助

错误是: -

System.ArgumentException: Complex DataBinding accepts as a data source either an IList or an IListSource.
   at System.Windows.Forms.ListControl.set_DataSource(Object value)

1 个答案:

答案 0 :(得分:1)

您当前的查询会生成IEnumerable<XElement>,但不会为您提供所需的属性。

   // not tested
   var res = from c in xmlDoc.Element("Clients").Descendants("Client")
   select new { Name=c.Element("Name").Value, ID = c.Element("ID").Value };

   ...
   cmb1.DataSource = res.ToList();

ID将是一个字符串。