0

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

2
  • can you debug and check whether str has anything and temp.Text is returning a valid value? Commented Dec 6, 2013 at 5:14
  • 1
    I don't see where you are actually filling the array. You are filling it correct? frmsetting[s] will always be null if you don't set it to anything. Commented Dec 6, 2013 at 5:16

2 Answers 2

4

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()
};
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.