0

I have code that generates textboxes when the user right-clicks on a panel. I need a way to allow the user to also remove/delete the textbox control that was created. This code is how I create the textboxes during runtime:

private void panel1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            Point cp = panel1.PointToClient(Cursor.Position);
            i++;
            TextBox text = new TextBox();
            text = new TextBox();
            text.Name = "user_textbox" + i.ToString();
            text.Size = new System.Drawing.Size(panel1l.Width, 30);               
            text.Location = new Point(0, cp.Y);  // puts box at current mouse position  
            panel1.Controls.Add(text);
            text.Focus();
        }

I found code to remove controls in another post, but it isn't working for what I need. That code is below, but it is designed to search and delete the control based on the name. What I'm hoping to be able to do is right-click on the textbox that was created, and have an option to delete it. Any help would be appreciated.

// this is code to remove controls using
// name of the control

foreach (Control ctrl in this.Controls) 
{
    if (ctrl.Name == "Textbox2")
      this.Controls.Remove(ctrl);
}
DaveB
  • 51
  • 7
  • Consider just making them invisible. – Ňɏssa Pøngjǣrdenlarp Mar 28 '19 at 23:42
  • @MakeStackOverflowGoodAgain I would still have the same problem, I'd need to be able to allow the user to do that with a right-click on the generated textbox. (Unless I'm missing something?) – DaveB Mar 28 '19 at 23:44
  • Are you talking about the popup menu when you right-click!? And it includes an "Delete" option!? – PiggyChu001 Mar 29 '19 at 00:27
  • @PiggyChu001 Not exactly. The "delete" option in there doesn't remove the actual control, just the data that's highlighted. I need to remove the entire control. Doesn't have to be a right click, just some way to delete the textbox that has focus. Thanks. – DaveB Mar 29 '19 at 00:35
  • 1
    Check out [Adding a right click menu to an item](https://stackoverflow.com/a/9823948/11043674). – PiggyChu001 Mar 29 '19 at 00:58
  • @PiggyChu001 - Thank you, I'm going to experiment with that. – DaveB Mar 29 '19 at 01:07

1 Answers1

0

After trial and error and a lot of reading, I found out that menu items don't remove the Focus from its current container. So, I have created a menu and added a "delete" button. It works great.

private void deleteCurrentScheduleToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (ActiveControl is TextBox)
        {
            this.panel1.Controls.Remove(ActiveControl);

        }
    }
DaveB
  • 51
  • 7