0

I have a simple button click method which sets a textbox's text to a viarable textFromTB.

private void Button1_Click(object sender, EventArgs e)
    {         
        string textFromTB = TextBox1.Text;
    }

If I run that once, its okay, it set the text for TextBox1 to textFromTB. But if I run that method second time it throws an NullReferenceExepction. Why is that?

I tried to initialize textbox like that

private void Button1_Click(object sender, EventArgs e)
    {         
        TextBox TextBox1 = new TextBox();
        string textFromTB = TextBox1.Text; // that line returns null
    }

but that sets TextBox1.Text to null or empty string. How can I change the code that it will work multiple times without exceptions?

Thanks in advance!

orglce
  • 493
  • 1
  • 6
  • 19
  • Try this : `TextBox1.Text="Some Text"; textFromTB=TextBox1.Text` – Thirisangu Ramanathan Nov 06 '14 at 12:24
  • No, it still throws error because that line: `TextBox TextBox1 = new TextBox();` somehow resets the textbox1 and it's text becomes null. And then at the end textFromTB is always null. – orglce Nov 06 '14 at 12:32
  • set `ID` for the TextBox1., `TextBox1.ID="txt1"; TextBox1.Text="Some Text"; String textFromTB="TextBox1.Text";` – Thirisangu Ramanathan Nov 06 '14 at 13:37
  • Do I have to import something because .ID does not work? – orglce Nov 06 '14 at 17:36
  • It gives me that error: `Error 7 'System.Windows.Forms.TextBox' does not contain a definition for 'ID' and no extension method 'ID' accepting a first argument of type 'System.Windows.Forms.TextBox' could be found (are you missing a using directive or an assembly reference?) – orglce Nov 07 '14 at 13:49
  • Look at this : http://stackoverflow.com/questions/21126116/error-when-trying-to-get-an-int-from-textbox – Thirisangu Ramanathan Nov 07 '14 at 13:52
  • No, it doesn't help me. He's variables are just named incorrectly. My are just fine. – orglce Nov 07 '14 at 13:59

1 Answers1

0

are you sure it's the textbox that is null and not textFromTB ?

Quentin
  • 107
  • 11