Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a StringCollection Setting

I am writing an application, and I want to store a list of files selected by the user. Currently, one of my settings is a StringCollection called filesToFetch, which is User scoped and contains the paths of all the files that the program should fetch. I have a button that allows the user to add new files to the list. This is the code for the button click event

private void button1_Click(object sender, EventArgs e)
{
    DialogResult result = openFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        Properties.Settings.Default.filesToFetch.Add(openFileDialog1.FileName);
        Properties.Settings.Default.Save();
    }
}

When I try to add a new file to the StringCollection, I get the error

NullReference Exception was unhandled

Object reference not set to an instance of an object.

I think that this may be happening because filesToFetch has not been initialized, but I'm not really sure. I could be wrong, but I thought that an object gets a name when it is initialized, and since my settings all get names at Design time, I assumed that they are automatically initialized when the program runs, but now I think I might be wrong about this. Is this the issue, or am i missing something else?

Here is a screen capture of my settings for reference.

Properties Settings

like image 754
Eric Avatar asked Nov 16 '12 15:11

Eric


2 Answers

If you want to enter values in the Settings GUI, on the far right there is a "..." button which allows you to enter the initial string values each separated on a line. It then converts that into XML as such:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <string>String1</string>
  <string>String2</string>
</ArrayOfString>

edit: Yes you need to initialize the StringCollection and my above answer is the way to do it using the GUI. Thought it would help people (like me) who stumbled on this post looking for a way to initialize a StringCollection setting like OP needed to do.

like image 191
Alan Wright Avatar answered Sep 28 '22 17:09

Alan Wright


I should probably explain a bit further. Let's say you were going to use a list of strings. You can declare:

IList<string> a;

At this point a = null and null does not have an Add method. If you initialize:

IList<string> a = new List<string>();

Now a = an empty list of strings. It will at this point have an Add method to use to add strings to the list.

like image 42
Kevin Avatar answered Sep 28 '22 17:09

Kevin