使用xml文件填充组合框

时间:2017-03-29 11:07:30

标签: c# xml

这是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";

    }

2 个答案:

答案 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")

中正确提及xml文档的路径
    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";
    }