【问题标题】:Trying to bind XML to a ComboBox using WinForm and C#尝试使用 WinForm 和 C# 将 XML 绑定到 ComboBox
【发布时间】:2016-02-25 18:42:46
【问题描述】:

文件名: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:

【问题讨论】:

  • 这一行中的"name" 是什么? LocationPosition = x.Attribute("name").Value
  • 我不知道。调试器不会显示值

标签: c# xml winforms exception-handling


【解决方案1】:

那是因为该 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-10
    • 2011-06-25
    • 2011-01-21
    • 1970-01-01
    • 2014-04-19
    • 2011-08-16
    • 2011-03-07
    • 1970-01-01
    相关资源
    最近更新 更多