Trying to bind XML to a ComboBox using WinForm and C#

人盡茶涼 提交于 2019-12-11 11:34:02

问题


File Name: 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>

I am trying to populate a combobox with the "text" from position. The id is not necessary at this time.

My C# Code

        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

The Error message says

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

回答1:


That because there isn't any name attribute in that xml string.

Change name to 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();


来源:https://stackoverflow.com/questions/35635630/trying-to-bind-xml-to-a-combobox-using-winform-and-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!