[英]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.