문제

Im unsure about how i can use a dictionary i create when i click a button which mean that i cannot reference to it from within another function. This is probably very basic, but i simply cannot remember how this is done.

This is the button that opens up a file dialog, which then reads each line inside the file, and stores the contents inside the dictionary:

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter = "Mod Pack Configuration file|*.mcf";
    openFileDialog1.Title = "Load Mod Pack Configuration File";
    openFileDialog1.ShowDialog();

    if (openFileDialog1.FileName != "")
    {
        Dictionary<string, string> loadfile =
        File.ReadLines(openFileDialog1.FileName)
            .Select(line => line.Split(';'))
            .ToDictionary(parts => parts[0], parts => parts[1]);
    }
}

Then afterwards i load a function, that places the loaded files, strings inside different controls within the form. However the below code doesnt work as "loaddfile" is not found:

public void getDefaultSettings()
{
    if (Properties.Settings.Default.modsDestDropDown != "") 
    {
        modsDestDropDown.SelectedIndex = Convert.ToInt32(loadfile['modsDestDropDown']);
    }
}

I could ofcourse write the function inside the button1 click event instead, but since i use this function across the program in other places, it would then give me some trouble later

도움이 되었습니까?

해결책

Define your dictionary in the class level, outside of your methods like this:

Dictionary<string, string> loadfile;

Then just initialize it in your method:

loadfile = File.ReadLines(openFileDialog1.FileName)
               .Select(line => line.Split(';'))
               .ToDictionary(parts => parts[0], parts => parts[1]);

다른 팁

loadFile is currently a local variable only available in the scope of button1_Click. If you want it available in more than one method you should make it a field on your class.

private Dictionary<string, string> loadfile;
private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter = "Mod Pack Configuration file|*.mcf";
    openFileDialog1.Title = "Load Mod Pack Configuration File";
    openFileDialog1.ShowDialog();

    if (openFileDialog1.FileName != "")
    {
        loadfile =
        File.ReadLines(openFileDialog1.FileName)
            .Select(line => line.Split(';'))
            .ToDictionary(parts => parts[0], parts => parts[1]);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top