GutierrezDev
GutierrezDev

Reputation: 1076

Problem passing data back from a child form

I got this problem:

private void loadStringToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringLoader frmStringLoader = new StringLoader();
            string test = frmStringLoader.Result;
            frmStringLoader.ShowDialog();
            MessageBox.Show(test.ToString());
        }

And the StringLoader Form:

 public partial class StringLoader : Form
    {

        private string result;
        public StringLoader()
        {
            InitializeComponent();
        }

        public string Result
        {
            get { return result; }
        }

        private void btnLoadString_Click(object sender, EventArgs e)
        {
            if ((txtString.Text != string.Empty))
            {
                result = txtString.Text;
            }
            this.Close();
        }
    }
}

This thing is gaving me a nullReferenceException (I know).

How to handle this thing? I just want to open a form, write a text and click a button to send the data back to the caller and close the form.

Thanks.

Upvotes: 0

Views: 649

Answers (2)

Dan Blanchard
Dan Blanchard

Reputation: 4054

You're grabbing the result before showing the form! Try

private void loadStringToolStripMenuItem_Click(object sender, EventArgs e)
    {
        StringLoader frmStringLoader = new StringLoader();
        frmStringLoader.ShowDialog();
        string test = frmStringLoader.Result;
        MessageBox.Show(test.ToString());
    }

Upvotes: 1

msergeant
msergeant

Reputation: 4801

You're setting your result before the dialog opens. Try reversing the two lines of code to look like this:

        frmStringLoader.ShowDialog();
        string test = frmStringLoader.Result;

Upvotes: 2

Related Questions