1

Instead of using a pre-made TextBox control in design.cs, I am using a programmatically-added TextBox. First, this TextBox is filled by the user, and with a button onClick method, the content is processed inside a method in another class file called from the onClick method. After that, I want to remove whatever is in the TextBox and make it empty like its initial state, but it is not quite working.

/*MainForm.cs*/
private TextBox tb;
private SubForm sf = new SubForm();
private void initTextBox(){
    tb = new TextBox();
    preExistingPanel.Controls.Add(tb); //attach the textbox onto a panel
}

private void MainForm_Load(object sender, EventArgs e){
    initTextBox();
}

private void button_Click(object sender, EventArgs e){
    string tbContent = tb.Text;
    sf.processData(tbContent);
}

public void EmptyTextBox(){
    tb.Text = "";        //This does not work, and nothing happens
}


/*SubForm.cs*/
public void processData(string tbContent){
    /*Do something with tbContent*/
    ...
    ...
    /*Here, I want to empty the textBox*/
    MainForm mf = new MainForm();
    mf.EmptyTextBox();
}

Can someone please help me find what is wrong with this code? I know that

EmptyTextBox()

method is called, but nothing happens.

JessicaD
  • 89
  • 3
  • 3
  • 8
  • What is the relation between preExistingPanel, main form and sub form? Without this information I am not sure anyone can help you – wnvko Aug 01 '17 at 03:56

1 Answers1

2

You are creating a brand new instance of MainForm in your processData method. One that does not have your programatically created TextBox in it (it is not shown/Load never called - and this would not be the correct way to access your MainForms anyway). So you will get a NullReferenceException when you call EmptyTextBox().

You can pass a reference of your MainForm to your SubForm's construtor (also remove your new MainForm line):

MainForm mf;
public SubForm (MainForm main)
{
    mf = main;
}
Broots Waymb
  • 4,713
  • 3
  • 28
  • 51
  • That makes perfect sense, thanks! But how can I fix this though? I know creating a new instance of each other in each other's class as a constructor causes StackOverFlowException. – JessicaD Jul 31 '17 at 20:58
  • Don't create new ones each time. Pass the reference. See edit. And for additional reference: https://stackoverflow.com/a/26862346/2957232 – Broots Waymb Jul 31 '17 at 20:59