文件名:位置.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();