user3003613
user3003613

Reputation: 37

using an array of Settings in C#

i want to write a program that somehow is like a designer where user can add textbox on the form and everything the user put into those textbox can be saved (like a setting) and after closing and opening the form again textboxs' text will remail unchanged.

so i decided to make a setting in project->settings and then make an array of it in my code. but whenever i want to access my settings it gives me an exception:

"An unhandled exception of type 'System.NullReferenceException' occurred in FormDesigner.exe"

here is my code from defining the array:

Settings[] formsetting=new Settings[3];

and here is my code for handling the textchanged event for everytext box: (i use the textboxs' tag to match the settings index with every textbox)

void t_TextChanged(object sender, EventArgs e)
        {
            TextBox temp = (TextBox)sender;
            int s =(int) temp.Tag;
            string str = temp.Text;
            frmsetting[s].text = str;
        }

the last line is where i get the error.

could someone explain to me what is the problem and how to fix it? and if my way is wrong could you please show my another way of doing this. thanks

Upvotes: 0

Views: 108

Answers (2)

Simon Whitehead
Simon Whitehead

Reputation: 65049

You haven't initialized the objects in the array.

Doing this:

Settings[] formsetting = new Settings[3];

..creates the array. All 3 are null though. Do this:

var formsetting = new Settings[3] {
    new Settings(),
    new Settings(),
    new Settings()
};

Upvotes: 4

Darren Kopp
Darren Kopp

Reputation: 77627

While you are initializing your array, you are not actually initializing any of the values. What you have currently is equivalent to the following:

Settings[] formsetting=new Settings[3];
formsetting[0] = null;
formsetting[1] = null;
formsetting[2] = null;

You need to initialize the value at the index you want to use before doing anything with it.

Upvotes: 3

Related Questions