none
How to delete dynamically created Textbox using delete key on keyboard? RRS feed

  • Question

  • I created dynamic textbox(es), picturebox(es) and whenever calling delete key to delete the picturebox or textbox, the delete effect is not happening. In fact, I have a Textbox and a small picture box on my form, along with a big picture box. I drag and drop text box and small picture box on to the big picture box. The boxes get created dynamically using 'new'. If I don't have the text box dragged and dropped, it is easy to delete the small picture box; but, i have to set textbox on the form to Enabled = false;. Otherwise, it doesn't delete or remove. Similarly, if I have dragged and dropped a textbox on to the big picture box, i am unable to even set Enable to 'false' ( though trying to set the same in the code doesn't have any effect on the drag dropped textbox). I have Googled for solution but found that all the examples used either a button or checkbox, through which, the deletion or removal of textbox could be effected. But I want to use delete key only and ensure the drag dropped dynamic textbox is deleted. How?

    Thanks in advance.

    • Moved by CoolDadTx Friday, November 22, 2019 2:36 PM Winforms related
    Thursday, November 21, 2019 2:37 PM

Answers

  • Hi jbwrks,

    Thanks for your feedback.

    You can also delete the textbox in textbox_KeyDown().

            private void textbox1_KeyDown(object sender, KeyEventArgs e)
            {
                if (e.KeyCode == Keys.Delete)
                {
                    TextBox textbox1 = (TextBox)this.Controls.Find("textbox1", true)[0];
                    this.Controls.Remove(textbox1);
                }
            }

    One more thing, in this code, as long as the textbox still exists, the picture box cannot be deleted because the cursor will always blink in the textbox.

    I solved this by adding this.ActiveControl = null in picture1_MouseDown ().

    And for your last question, textbox1_MouseUp will be executed after textbox1_MouseDown, so when you use (TextBox) this.Controls.Find ("textbox1", true) [0] in textbox1_MouseUp, the textBox has been deleted.

    By the way, you can insert code block by using this button:


    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.




    Tuesday, November 26, 2019 9:50 AM

All replies

  • Hello,

    You need to post current code so those who want to assist know what you have so far.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, November 21, 2019 3:34 PM
    Moderator
  • As Karen says, sample code would be helpful.

    If you are trying to make something happen on a key press, you need to create a Key Down event on your form. Set the form's KeyPreview property to True. Then in the KeyDown event, check to see what key was pressed. If DEL was pressed then run the sample code that you found when a button is clicked.

    There are various (to put it mildly) examples on detecting when the Del key is pressed. Google or Bing is your friend :-). Saga

    Edited: There is another event called KeyPress. This is great for detecting letters, numbers and punctuation symbols, the DEL key, not so much.


    You can't take the sky from me




    • Edited by SagaV9 Thursday, November 21, 2019 8:09 PM
    Thursday, November 21, 2019 7:47 PM
  • Thanks Karen.

    Here's part of the code:

     virtTxtBox.MouseDown += (ss, ee) =>
                    {
                        if (ee.Button == MouseButtons.Left)
                        {
                            //this.textBox1.Enabled = false;
                            firstPoint = Control.MousePosition;
                            if (virtTxtBox.BorderStyle == BorderStyle.None)
                            {
                                virtTxtBox.BorderStyle = BorderStyle.FixedSingle;
                            }
                            else
                            if (virtTxtBox.BorderStyle == BorderStyle.FixedSingle)
                            {// virtTxtBox.MouseEnter += (ssh, eeh) =>
                                {
                                    KeyDown += (o, e2) =>
                                        {
                                            virtTxtBox.Focus().Equals(false);
                                            if (e2.KeyCode == Keys.Delete)
                                            {
                                                TextBox TxtBox = (sender as TextBox);
                                                    //if (virtTxtBox.BorderStyle == BorderStyle.FixedSingle)
                                                    {
                                                    //gets index of the Button.
                                                    int index = int.Parse(TxtBox.Name.Split('_')[1]);
                                                    label1.Text = index.ToString();
                                                    //Textbox is found and removed using index
                                                    pictureBox1.Controls.Remove(pictureBox1.Controls.Find("txt_" + index, true)[0]);
                                                    pictureBox1.Controls.Clear();
                                                    virtTxtBox.Dispose();
                                                }
                                            }
                                        };
                                    virtTxtBox.BorderStyle = BorderStyle.None;
                                };
                            }
                            //virtTxtBox.Enabled = false;
                        }
                    };

    Friday, November 22, 2019 4:41 AM
  • Thanks Saga.

    Above in Karen's comment box is my code, though only part of it, but that is where I am trying to experiment in various ways, to get the virtual text box removed out of the bigger picturebox (pictureBox1).

    Friday, November 22, 2019 4:47 AM
  • Hi jbwrks,

    Thank you for posting here.

    Based on your description, I wrote a sample code to remove the small picturebx that was dragged onto the large pictureBox and did not encounter the problem you mentioned.

        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Button1_Click(object sender, EventArgs e)
            {
    
            }
            private bool isDragging = false;
            private int currentX, currentY;
            Rectangle dropRect = new Rectangle(180, 180, 60, 60);
            private void Form1_Load(object sender, EventArgs e)
            {
                PictureBox picture1 = new PictureBox();
                picture1.Location = new Point(100, 200);
                picture1.Name = "picture1";
                picture1.Height = 100;
                picture1.Width = 100;
                picture1.BackColor = Color.Red;
                picture1.MouseDown += new MouseEventHandler(picture1_MouseDown);
                picture1.MouseUp += new MouseEventHandler(picture1_MouseUp);
                picture1.MouseMove += new MouseEventHandler(picture1_MouseMove);
                
                this.Controls.Add(picture1);
    
                TextBox textbox1 = new TextBox();
                textbox1.Location = new Point(100, 100);
                textbox1.Name = "textBox1";
    
                this.Controls.Add(textbox1);
               
                PictureBox picture2 = new PictureBox();
                picture2.Location = new Point(400, 100);
                Name = "picture2";
                picture2.Height = 300;
                picture2.Width = 300;
                picture2.BackColor = Color.Blue;
                this.Controls.Add(picture2);
            }
    
            private void picture1_MouseDown(object sender, MouseEventArgs e)
            {
                PictureBox picture1 = (PictureBox)this.Controls.Find("picture1", true)[0];
                isDragging = true;
                currentX = e.X;
                currentY = e.Y;
                if (e.Button == MouseButtons.Left )
                {
                    KeyDown += (o, e2) =>
                    {
                        if (e2.KeyCode == Keys.Delete)
                        {
                            this.Controls.Remove(picture1);
                        }
                    };
                }
            }
            private void picture1_MouseMove(object sender, MouseEventArgs e)
            {
                PictureBox picture1 = (PictureBox)this.Controls.Find("picture1", true)[0];
                if (isDragging)
                {
                    picture1.Top = picture1.Top + (e.Y - currentY);
                    picture1.Left = picture1.Left + (e.X - currentX);
                }
            }
            private void picture1_MouseUp(object sender, MouseEventArgs e)
            {
                PictureBox picture1 = (PictureBox)this.Controls.Find("picture1", true)[0];
                isDragging = false;
                Console.WriteLine(dropRect.Contains(picture1.Bounds));
            }
    }
    

    Result:

    If this does not match your requirements, please describe your problem in more detail, or show some screenshots to help us understand your question.

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, November 22, 2019 8:38 AM
  • Dear Timon,

    Your efforts are highly appreciated. I could do the picture box drag, drop and delete. But there was problem with text box drag, drop and delete. Also, while dragging, it should leave behind a copy of the respective control, to be used for subsequent drag drops. In such scenario, if I have dragged and dropped 4 or 5 text boxes and I wanted to delete the secondly dropped or thirdly dropped text box after having dropped 4 or 5 text boxes, I am unable to achieve this. Also, while the textbox is available on the big picturebox, i am unable to delete even the small picture box which was dragged and dropped on to the big picture box. I hope I made my issue clear here. Any help!?! Thank you dear.

    Friday, November 22, 2019 8:53 AM
  • Well! I don't think there is a solution for this problem of dynamically removing or deleting textbox(s) without the help of a button or checkbox associated with it.

    I had observed that if any of the textboxes found active (cursor blinking in the textbox's input area), it is difficult to effect a remove/delete, not only on a textbox but also on any other control created dynamically.  

    Even otherwise, I am wondering how the associated button or checkbox could remove an active textbox, as I found the cursor blinking in the textbox's input area!!!

    Any thoughts?

    Sunday, November 24, 2019 6:22 AM
  • Dear Timon,

    I have something interesting to share.

    I tried executing your code as it is. Unfortunately, I am unable to delete even the red picturebox, while I am able to move, both, picturebox and textbox.

    Any help on this, why am i getting such unusual behavior!?

    Thank you.

    Sunday, November 24, 2019 7:18 AM
  • Dear Timon,

    An update!

    I implemented your code and achieved the textbox delete/removal but only by setting 'Enabled' property of the textbox to 'false'.

    Now my query is, what if I created more than 1 textbox on the big picture and I want to delete only one of them (probably and particularly textbox1, if both, textbox1 and textbox2 are created). In such scenario, how do i proceed?

    Awaiting reply.

    Thank you.


    • Edited by jbwrks Sunday, November 24, 2019 9:39 AM
    Sunday, November 24, 2019 8:06 AM
  • Hi jbwrks,

    Thanks for your feedback.

    One idea, you can click on the testBox you want to delete, the cursor will flash in this textBox, then use this.ActiveControld to get the textbox and delete it.

    Best Reagards, 

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, November 25, 2019 9:21 AM
  • Hi Timon,

    I tried your latest suggestion. It is not working. One thing I am observing is that if the textbox control is 'Enabled' to 'false', the desired delete effect happens. But then, when more than 1 textbox are available, I need to put all textboxes to Enabled=false and then if I want them to come back to normal state where I can edit their text contents, I am unable to bring them back to life.

    Very tricky and troublesome!

    Monday, November 25, 2019 9:41 AM
  • Dear Timon,

    After lot of experimentation, I am unable to get the delete key do the job of deleting the textbox.

    But, the mouse_down is able to delete the active textbox!!! Please see the code attached below.

    How?!

    Quiet intriguing!!!

    Of course, I am a newbie to C#.net. But I would like to know why such a behavior! Also, I have commented on another intriguing behavior of Find(...) when used with this.Controls. As you can see in the code, the same works at only one place and that is in the mouse_down function.

    Anybody else who is C#.net expert, including Microsoft may also please explain for everybody's knowledge enhancement.

    Thank You.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    namespace WindowsFormsApp35
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private void Button1_Click(object sender, EventArgs e)
            {

            }
            private bool isDragging = false;
            private int currentX, currentY;
            Rectangle dropRect = new Rectangle(180, 180, 60, 60);

            private void picture1_MouseDown(object sender, MouseEventArgs e)
            {
                TextBox textbox9 = new TextBox();

                PictureBox picture1 = (PictureBox)this.Controls.Find("picture1", true)[0];
                isDragging = true;
                currentX = e.X;
                currentY = e.Y;
                if (e.Button == MouseButtons.Left)
                {
                    picture1.BorderStyle = BorderStyle.FixedSingle;
                    KeyDown += (o, e2) =>
                    {
                        if (e2.KeyCode == Keys.Delete)
                        {
                            label1.Text = "pic del";

                            if (picture1.BorderStyle == BorderStyle.FixedSingle)
                            this.Controls.Remove(picture1);

                        }
                    };
                }
            }
            private void textbox1_MouseDown(object sender, MouseEventArgs e)
            {
                TextBox textbox1 = (TextBox)this.Controls.Find("textbox1", true)[0];
                //TextBox textbox1 = new TextBox();
                this.ActiveControl = textbox1;
                
                isDragging = true;
                currentX = e.X;
                currentY = e.Y;
                        
                if (e.Button == MouseButtons.Left)
                {
                    label1.Text="Text del";
                    //At this point for below line, the excution happens i.e., the textbox gets deleted which is not what is intended
                    this.Controls.Remove(textbox1);

                    //At this point, it is intended that upon pressing 'delete' key on the keyboard, the textbox should 
                    //get deleted, but not happening
                    KeyDown += (o, e2) =>
                    {
                        if (e2.KeyCode == Keys.Delete)
                        {
                            this.Controls.Remove(textbox1);
                        }
                    };
                }
            }

            private void picture1_MouseMove(object sender, MouseEventArgs e)
            {
                PictureBox picture1 = (PictureBox)this.Controls.Find("picture1", true)[0];
                if (isDragging)
                {
                    picture1.Top = picture1.Top + (e.Y - currentY);
                    picture1.Left = picture1.Left + (e.X - currentX);
                }
            }
            private void textbox1_MouseMove(object sender, MouseEventArgs e)
            {
                    TextBox textbox0 = new TextBox();

                    if (isDragging)
                    {
                        textbox0.Top = textbox0.Top + (e.Y - currentY);
                        textbox0.Left = textbox0.Left + (e.X - currentX);
                    }
            }

            private void picture1_MouseUp(object sender, MouseEventArgs e)
            {
                PictureBox picture1 = (PictureBox)this.Controls.Find("picture1", true)[0];
                isDragging = false;
                Console.WriteLine(dropRect.Contains(picture1.Bounds));
            }

            private void Form1_Load_1(object sender, EventArgs e)
            {
                    PictureBox picture1 = new PictureBox();
                    picture1.Location = new Point(100, 200);
                    picture1.Name = "picture1";
                    picture1.Height = 100;
                    picture1.Width = 100;
                    picture1.BackColor = Color.Red;

                    picture1.MouseDown += new MouseEventHandler(picture1_MouseDown);
                    picture1.MouseUp += new MouseEventHandler(picture1_MouseUp);
                    picture1.MouseMove += new MouseEventHandler(picture1_MouseMove);

                    this.Controls.Add(picture1);

                    TextBox textbox1 = new TextBox();
                    textbox1.Location = new Point(100, 100);
                    textbox1.Name = "textBox1";

                    textbox1.MouseDown += new MouseEventHandler(textbox1_MouseDown);
                    textbox1.MouseUp += new MouseEventHandler(textbox1_MouseUp);
                    textbox1.MouseMove += new MouseEventHandler(textbox1_MouseMove);

                    this.Controls.Add(textbox1);
                    textbox1.Enabled = true;

                    PictureBox picture2 = new PictureBox();
                    picture2.Location = new Point(400, 100);
                    Name = "picture2";
                    picture2.Height = 300;
                    picture2.Width = 300;
                    picture2.BackColor = Color.Blue;
                    this.Controls.Add(picture2);
            }

            private void textbox1_MouseUp(object sender, MouseEventArgs e)
            {
               //TextBox textbox1 = (TextBox)this.Controls.Find("textbox1", true)[0];
               //The above line giving error as "SystemIndexOutOfRange: 'Index was outside the bounds of the array.'
               //In fact, the above error was occurring at all instances of that code except in textbox1_MouseDown(obje......){...}
               //Don't know why!!!
                isDragging = false;
                //Console.WriteLine(dropRect.Contains(textbox1.Bounds));
            }
        }
    }

    Tuesday, November 26, 2019 5:45 AM
  • Hi jbwrks,

    Thanks for your feedback.

    You can also delete the textbox in textbox_KeyDown().

            private void textbox1_KeyDown(object sender, KeyEventArgs e)
            {
                if (e.KeyCode == Keys.Delete)
                {
                    TextBox textbox1 = (TextBox)this.Controls.Find("textbox1", true)[0];
                    this.Controls.Remove(textbox1);
                }
            }

    One more thing, in this code, as long as the textbox still exists, the picture box cannot be deleted because the cursor will always blink in the textbox.

    I solved this by adding this.ActiveControl = null in picture1_MouseDown ().

    And for your last question, textbox1_MouseUp will be executed after textbox1_MouseDown, so when you use (TextBox) this.Controls.Find ("textbox1", true) [0] in textbox1_MouseUp, the textBox has been deleted.

    By the way, you can insert code block by using this button:


    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.




    Tuesday, November 26, 2019 9:50 AM
  • Thank you very much Timon.

    Great job!

    But, I want to know why KeyDown += (o, e2) =>  doesn't work here specifically while the same is working without any issue in picturebox1_MouseDown?!

    Now, I shall try if the same works while there are 2 or more textboxes created dynamically. And I shall share the result with you, here.

    Anyways, kudos to you.

    I will now disturb you for further queries. Is that fine with you?

    I have much more to do and if I get stuck at any point, I shall pose the problem to you for solution from you.

    Have great time ahead, Timon.

    Regards

    Vivek

    Tuesday, November 26, 2019 11:06 AM
  • Dear Timon,

    For the observation (please refer to my comment on 25th November at 9:41AM) that the textbox 'Enabled' to 'false' allows picture box to be deleted, how to bring the textbox back to life? I want the text box back to life, so that I can either append the text contained in that textbox or even alter the text contents of that text box.

    I tried setting the textbox to ActiveControl but it doesn't help.

    Hope I am not troubling you with my queries if you feel that they are silly queries to be asked. After trying all the available code that VS offers, I am posing any of my queries.

    Thank you.

    Vivek


    • Edited by jbwrks Thursday, November 28, 2019 8:53 AM
    Thursday, November 28, 2019 8:51 AM
  • Dear Timon,

    I got the textbox to life by simply making textbox.enabled=true by checking if enabled is true or false. Without the if statement it hadn't worked initially and hence my earlier query.

    Vivek

    Thursday, November 28, 2019 9:50 AM