使用XML文件填充组合框 [英] Populate a combobox with an XML file
本文介绍了使用XML文件填充组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
This is the XML file
<Users>
<User userID="4" username="lol" password="lol" usertype="Guest" />
</Users>
我的尝试:
What I have tried:
the code i tried
private void ExistingUser_Load(object sender, EventArgs e)
{
var xml = XElement.Load("XMLFile1.xml");
comboBox1.DisplayMember = "userID";
}
推荐答案
您没有将任何内容从XML文件分配到组合框。
您可以通过多种方式实现目标...
1.使用System.Xml.Linq ;
You are not assigning anything from the XML file to the comboBox.
There are a variety of ways you can achieve your target...
1. using System.Xml.Linq;
XElement users = XElement.Load(@"c:\temp\temp.xml");
foreach (var urlElement in users.Elements("User"))
comboBox3.Items.Add(urlElement.Attribute("userID").Value);
2。使用System.Xml; // XmlDocument
2. using System.Xml; // XmlDocument
XmlDocument doc = new XmlDocument();
doc.Load(@"c:\temp\temp.xml");
XmlNodeList userList = doc.SelectNodes("Users/User");
foreach (XmlNode xn in userList)
comboBox1.Items.Add(xn.Attributes["userID"].Value);
3。使用System.Xml; // XmlTextReader
3. using System.Xml; // XmlTextReader
using (XmlTextReader xmdatareader = new XmlTextReader(@"c:\temp\temp.xml"))
{
DataSet ds = new DataSet();
ds.ReadXml(xmdatareader);
comboBox2.DataSource = ds.Tables[0];
comboBox2.DisplayMember = "userID";
}
注意所有这些选项我应该检查空值!
Note with all of these options I should have been checking for nulls!
这篇关于使用XML文件填充组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文