简体   繁体   中英

c# winforms Form Load ComboBox DropDownList get value from XML file

XML File:

<?xml version="1.0" encoding="utf-16"?>
<XMLFILE>
 <Active>0</Active>
 <Hits_Method>1</Hits_Method>
</XMLFILE>

What i'm trying to do is on Form1_Load get the value of ComboBox4 from XML File (Hits_Method) and when the program start to show me the value. i try something like this but didn't work out

// ------------------- StartUP Load
private void Form1_Load(object sender, EventArgs e)
{
    // --------------- Read XML File / Data: Settings_Ads_General
    String xmlfile = "Settings_General.xml";
    XmlTextReader xreader = new XmlTextReader(xmlfile);

    string comboBox4Value = xreader.GetAttribute("Hits_Method");
    comboBox4.SelectedIndex = comboBox4Value;

}

Try this instead:

    private void Form1_Load(object sender, EventArgs e)
    {
        // --------------- Read XML File / Data: Settings_Ads_General
        String xmlfile = "Settings_General.xml";
        XmlDocument doc = new XmlDocument();
        doc.Load(xmlfile);

        string comboBox4Value = doc.SelectSingleNode("XMLFILE/Hits_Method").InnerText;
        comboBox4.SelectedIndex = Convert.ToInt32(comboBox4Value);

    }

The SelectSingleNode method extracts data based on an XPath expression. And "XMLFILE/Hits_Method" is the XPath that leads to your value.

I will use XmlDocument and XmlNode classes.

{
    String sPath = "file.xml"
    XmlDocument doc = new XmlDocument();
    doc.Load(sPath)
    XmlNode node = doc.SelectSingleNode("XMLFILE/Hits_Method");
    if (node != null)
        comboBox4.SelectedIndex = node.InnerText;
}

Check out this link courtesy of MSDN. It provides a good example of how to get the value you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM