MiNi
MiNi

Reputation: 1

C# remove last dynamically created textbox

Almost totally noob here. Im stucked. I know how to delete all dc textboxes but have no idea how to delete only last created one. Thx

piece of my code:

int B = 1;
    public void NovIntRazd()
    {
        TextBox txt = new TextBox();
        this.Controls.Add(txt);
        txt.Top = B * 30;
        txt.Left = 26;
        txt.Height = 20;
        txt.Width = 65;
        txt.Name = "txtIntRazd" + this.B.ToString();
        B++;
    }

Upvotes: 0

Views: 147

Answers (1)

Luaan
Luaan

Reputation: 63772

If you only need to ever remove one textbox, you can just keep the reference to the last one:

int B = 1;
TextBox txt;
public void NovIntRazd()
{
    txt = new TextBox();
    this.Controls.Add(txt);
    txt.Top = B * 30;
    txt.Left = 26;
    txt.Height = 20;
    txt.Width = 65;
    txt.Name = "txtIntRazd" + this.B.ToString();
    B++;
}

public void RemoveLast()
{
    if (txt == null) return;
    Controls.Remove(txt);
    txt = null;
}

Alternatively, a good practice is to put dynamically created controls in their own container, like a panel. It sounds like your case is a perfect use for a FlowLayoutPanel, which will handle control positioning too. When you remove any control, all the others are automatically moved around to the right places.

Then to remove the last added control, you can just do

if (pnl.Controls.Count > 0) pnl.Controls.RemoveAt(pnl.Controls.Count - 1);

If you really want to keep the controls mixed up in the top-level form, you can easily organize the dynamic textboxes by using a Stack:

Stack<TextBox> textboxes = new Stack<TextBox>();

public void NovIntRazd()
{
    var txt = new TextBox()
       {
         Top = (textboxes.Count + 1) * 30, 
         Left = 26,
         Height = 20,
         Width = 65,
         Name = "txtIntRazd" + (textboxes.Count + 1).ToString()
       };

    this.Controls.Add(txt);
    textboxes.Push(txt);
}

public void RemoveLast()
{
    if (textboxes.Count == 0) return;
    Controls.Remove(textboxes.Pop());
}

Upvotes: 1

Related Questions