简体   繁体   中英

Loading an XML file in C# win forms

In my program, the user can save the settings with a button. The store works. Loading the settings does not work quite right. I have a problem when loading the rule. I have several rules as a list. I dont know how to specify the index. Can anybody help me please?

Methods to save/load the settings:

private void SaveUserConfigButton_Click(object sender, EventArgs e)
    {
        var userConfig = new UserConfig();

        userConfig.RandomPopulation = (int)_probability;
        userConfig.Rule = _gameOfLife.NextGenerationRule.RuleName;
        userConfig.Speed = _timer.Interval;
        userConfig.UseBoundary = _gameOfLife.UseBoundary;
        SaveUserConfig(userConfig);
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
        var userConfig = LoadUserConfig(_path);

        InputRandomPopulationNumbericUpDown.Value = userConfig.RandomPopulation;
        SelectRulesComboBox.SelectedItem = _rules[5];  // <-- here is the problem
        SpeedTrackBar.Value = userConfig.Speed;
        BoundaryCheckBox.Checked = userConfig.UseBoundary;
    }

My english is not so good, I hope it is understandable.

Assuming userConfig.Rule is the name of the rule you want selected in the SelectRulesComboBox and each instance of a rule has a property named Name what you need to do is find the index of userConfig.Rule within the _rules collection.

If _rules is a List<T> then you can use the FindIndex method:

SelectedRulesCombobox.SelectedIndex = _rules.FindIndex(r => r.Name == userConfig.Rule);

Otherwise, you can just project each rule alongside its index within _rules collection and get the first one that has Name == userConfig.Rule :

SelectedRulesCombobox.SelectedIndex = _rules.Select((rule, index) => new
{
    Rule = rule,
    Index = index
})
.First(x => x.Rule.Name == userConfig.Rule)
.Index;

Keep in mind though that the code above will throw an exception if no rule was found with Name == userConfig.Rule .

Why not use datatable & WriteXml and ReadXml ?

void writeResults()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("configID");
    dt.Columns.Add("configValue");

    //Other code you want to add

    //Then add row for each setting
    Datarow r  = dt.NewRow();
    r["configID"]= "Speed"; //e.g. Speed  
    r["configValue"]=_timer.Interval.ToString();  
    dt.Rows.Add(r);
    // snip

    //then save datatable to file
    dt.TableName="UserConfigs";
    dt.WriteXml(@"filename_goes_here");
}

To read settings from file is even easier :

void readSettings()
{
    DataTable dt = new DataTable();
    dt.ReadXml(@"filename_goes_here");

    for(int i = 0; i < dt.Rows.Count; i++)
    {
        switch(dt.Rows[i][0])
        {
            case "Speed":
                try
                {
                    _timer.Interval=Int32.Parse(dr.Rows[i][1]);
                }
                catch
                {
                    // we've got a problem !
                }

                break;
            default:break;
        }
    }
}

Edit: That's not optimal way, but it can get you started. Always try/catch every single block where you're validating data from xml - never trust user input, Nuff said.

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