0

I have a string array

public: array<String ^> ^ sss;
public:
    Form1(void)
    {
        InitializeComponent();
        //
        //TODO: Add the constructor code here
        //
        array<String ^> ^ sss = gcnew array<String ^>(3);
        sss[0]="asdasd";
        sss[1]="s115ss";
        sss[2]="s115ss";
    }

I need to show the 1st element into a textbox.

I used

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

             textBox2->Text = sss[0];
         }

Vc++ gave System.NullReferenceException. Why? And how to fix it?

The error:

An unhandled exception of type 'System.NullReferenceException' occurred in test000.exe Additional information: Object reference not set to an instance of an object.

2
  • 2
    Please add the full stack trace. Based on the information you've provided I am willing to bet that the NullReference is the object textbox not s Commented Apr 21, 2012 at 5:02
  • Not Right. The following code works in my program textBox2->Text = "11111"; Commented Apr 21, 2012 at 5:14

1 Answer 1

1

Your code shouldn't compile, unless you also have a field called sss. If that's the case, you want to set the value of that field in your constructor, not of some unrelated local variable with the same name:

array<String ^> ^ sss;

public:
    Form1(void)
    {
        InitializeComponent();

        sss = gcnew array<String ^>(3);
        sss[0]="asdasd";
        sss[1]="s115ss";
        sss[2]="s115ss";
    }
Sign up to request clarification or add additional context in comments.

3 Comments

I am sorry I forget to add that in my post. I have that code in my code (just edited my post), but my program does not work.
Like I said, you want to set the field, not some local variable in the constructor. Change the line where you gnew the array to the one in my answer.
You are right. I am sorry that I did not catch what you mean at the first time.

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.