0

I am generating a RichTextBox and a button with another button. When the generated button is clicked, I want to delete the RichTextBox and itself.

static int i = 1;

private void generate_Click(object sender, EventArgs e)
{            
   RichTextBox text = new RichTextBox();
   Button delete = new Button();

   this.Controls.Add(text);
   this.Controls.Add(delete);
   i++;
}
3
  • You can set the name for the control to something the delete method can use to find the control later using Find(). You can also store a reference to the control in a class member that the delete method can use. Commented Jan 7, 2019 at 19:17
  • This might help stackoverflow.com/questions/13888558/… Commented Jan 7, 2019 at 19:18
  • Your declarations are in the wrong scope. "text" and "delete" (terrible names, by the way) should be declared at the form level. Use text.Dispose(); and delete.Dispose(); to get rid of them. Simply calling this.Controls.Remove(...) is not enough since it would keep the controls in memory. Commented Jan 7, 2019 at 19:49

2 Answers 2

1

You can remove a control from a form like this:

private void generate_Click(object sender, EventArgs e)
{            
  RichTextBox text = new RichTextBox();
  Button delete = new Button();

  this.Controls.Add(text);
  this.Controls.Add(delete);
  i++;

  //---- Remove Part --------

  this.Controls.Remove(text);

  //------------------------
}

I hope this helps you.

Sign up to request clarification or add additional context in comments.

Comments

0

You can declare the field in your form

RichTextBox m_Control;

Then, assign it

private void generate_Click(object sender, EventArgs e)
{            
    RichTextBox text = new RichTextBox();
    Button delete = new Button();
    m_Control = text;

    this.Controls.Add(text);
    this.Controls.Add(delete);
    i++;
}

when you need to remove it, you can do

this. Controls. Remove(m_Control) ;

1 Comment

You really, really need to call Dispose() on the controls you added. + You're not removing the Button, here. Dispose of both, this will also remove them from the Parent container. You could also use a Lambda, something like: delete.Click += (o, evt) => { text.Dispose(); delete.Click -= (obj, ev) => { }; delete.Dispose(); };

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.