JessicaD
JessicaD

Reputation: 119

Unable to access a programmatically-added control (C#)

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.

Upvotes: 1

Views: 75

Answers (1)

Broots Waymb
Broots Waymb

Reputation: 4826

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;
}

Upvotes: 2

Related Questions