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++;
}
  • You can set the name for the control to something the delete method can use to find the control later using [Find()](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.controlcollection.find?redirectedfrom=MSDN&view=netframework-4.7.2#System_Windows_Forms_Control_ControlCollection_Find_System_String_System_Boolean_). You can also store a reference to the control in a class member that the delete method can use. – itsme86 Jan 07 '19 at 19:17
  • This might help https://stackoverflow.com/questions/13888558/removing-dynamic-controls-from-panel – hce Jan 07 '19 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. – LarsTech Jan 07 '19 at 19:49

2 Answers2

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.

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) ;
Yennefer
  • 5,704
  • 7
  • 31
  • 44
  • 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(); }; ` – Jimi Jan 07 '19 at 21:13