繁体   English   中英

尝试使用WinForm和C#将XML绑定到ComboBox

[英]Trying to bind XML to a ComboBox using WinForm and C#

文件名:location.xml

<?xml version="1.0" encoding="utf-8" ?>
<locations>
  <location id="1" position="Holiday" />
  <location id="2" position="Time Off" />
  <location id="3" position="Training" />
</locations>

我正在尝试使用位置中的“文本”填充组合框。 该ID暂时不需要。

我的C#代码

        var obj = XDocument.Load("location.xml");            
        comboBox1.DisplayMember = "LocationPosition";
        comboBox1.ValueMember = "LocationID";

        comboBox1.DataSource = obj.Descendants("location").Select(x => new
        {
            LocationPosition = x.Attribute("name").Value,
            LocationID = x.Attribute("id").Value
        }).ToList(); // Crashing here

错误消息说

System.NullReferenceException was unhandled
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=CalendarSharing
  StackTrace:

那是因为该xml字符串中没有任何name属性。

name更改为position

    var obj = XDocument.Load("location.xml");            
    comboBox1.DisplayMember = "LocationPosition";
    comboBox1.ValueMember = "LocationID";

    comboBox1.DataSource = obj.Descendants("location").Select(x => new
    {
        LocationPosition =x.Attribute("position").Value,
        LocationID =  x.Attribute("id").Value
    }).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM