[英]Trying to bind XML to a ComboBox using WinForm and C#
File Name: location.xml 文件名: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. 该ID暂时不需要。
My C# Code 我的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
The Error message says 错误消息说
System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=CalendarSharing
StackTrace:
That because there isn't any name
attribute in that xml string. 那是因为该xml字符串中没有任何name
属性。
Change name
to position
: 将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.