这是XML文件
<Users>
<User userID="4" username="lol" password="lol" usertype="Guest" />
</Users>
我试过的代码
private void ExistingUser_Load(object sender, EventArgs e)
{
var xml = XElement.Load("XMLFile1.xml");
comboBox1.DisplayMember = "userID";
}
答案 0 :(得分:1)
加载到DataSet
并将其用作Combobox的DataSource
:
DataSet dataSet = new DataSet();
dataSet.ReadXml("XMLFile1.xml");
this.comboBox1.DataSource = dataSet.Tables[0];
this.comboBox1.DisplayMember = "userID";
答案 1 :(得分:0)
尝试以下代码完美无缺。您需要在doc.Load("path")
。
private void Form1_Load(object sender, EventArgs e)
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\WindowsFormsApplication1\WindowsFormsApplication1\XMLFile1.xml");
XmlNodeList elemList = doc.GetElementsByTagName("User");
for (int i = 0; i < elemList.Count; i++)
{
string attrVal = elemList[i].Attributes["userID"].Value;
dictionary.Add(Convert.ToInt32(attrVal), attrVal);
}
comboBox1.DataSource = new BindingSource(dictionary, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
}