Adding TextBoxes via program

Category: c# general

Question

Troy22222 on Fri, 24 Aug 2018 20:21:45


Is it possible to add/delete textBoxes to/from a windows form?

Tac


tac

Replies

Kareninstructor on Fri, 24 Aug 2018 20:47:20


Your answer is 'yes' but adding and removal is only part of what you would need e.g.

  • Logic to name the control(s)
  • Code to obtain values from the control(s)
  • Code to valdate (may be, maybe not).

My point is you should spell out what you need overall and which version of Visual Studio is being used.

In closing, the following example creates dynamic buttons which may be more than you need (thinking replace buttons with TextBox).

Troy22222 on Sat, 25 Aug 2018 02:19:02


Karen:

I am running VS 2015.

I did find something on Youtube.

It works well for the 1st textbox however I can't get it to continue to insert others.

Each "ADD" needs to insert 5 textboxes.

What follows is one attempt that failed. Again if I just run one (anyone) it works.

Why does it only allow to insert one (1) textbox?

Any ideas?

int top_align = 1;

TextBox txt1 = new TextBox(); TextBox txt2 = new TextBox(); TextBox txt3 = new TextBox(); TextBox txt4 = new TextBox(); TextBox txt5 = new TextBox();

        private void btnAddText1_Click(object sender, EventArgs e)
        {
            add_txtbx1();
            add_txtbx2();
            add_txtbx3();
            add_txtbx4();
            add_txtbx5();
        }
       public TextBox add_txtbx1()
        {     
            this.Controls.Add(txt1);
            txt1.Top = top_align * 535;
            txt1.Left = 12;
            txt1.Width = 114;
            txt1.Height = 28;
            txt1.Name = "Testtext1" + this.top_align.ToString();
            top_align = top_align + 1;
            return txt1;
            }

        public TextBox add_txtbx2()
        {
            this.Controls.Add(txt2);
            txt2.Top = top_align * 535;
            txt2.Left = 132;
            txt2.Width = 463;
            txt2.Height = 22;
            txt2.Multiline = true;
            txt2.Name = "Testtext2" + this.top_align.ToString();
            top_align = top_align + 1;
            return txt2;
        }

        public TextBox add_txtbx3()
        {
            this.Controls.Add(txt3);
            txt3.Top = top_align * 535;
            txt3.Left = 601;
            txt3.Width = 71;
            txt3.Height = 28;
            txt3.Name = "Testtext3" + this.top_align.ToString();
            top_align = top_align + 1;
            return txt3;
        }
        public TextBox add_txtbx4()
        {
            this.Controls.Add(txt4);
            txt4.Top = top_align * 535;
            txt4.Left = 678;
            txt4.Width = 120;
            txt4.Height = 28;
            txt4.Name = "Testtext4" + this.top_align.ToString();
            top_align = top_align + 1;
            return txt4;
        }
        public TextBox add_txtbx5()
        {
            this.Controls.Add(txt5);
            txt5.Top = top_align * 535;
            txt5.Left = 804;
            txt5.Width = 134;
            txt5.Height = 28;
            txt5.Name = "Testtext5" + this.top_align.ToString();
            top_align = top_align + 1;
            return txt5;
        }


The 1st row is set on the form. The second row I'm attempting to insert 5 textboxes but only one shows.

Troy22222 on Sat, 25 Aug 2018 02:29:11


Karen:

Never mind, I figured it out.

I had to eliminate all but the last ""  top_align = top_align + 1;  "" instruction(s).

Can you help me figure out how to set the font style and size in code?

Kareninstructor on Sat, 25 Aug 2018 10:11:36


The following in this case creates 10 TextBox controls on a FlowLayoutPanel. If you happen to be using VS2017 the code will work fine but if using an earlier version you may have to tweak the code slightly. Full project source code

Earlier VS the top line will not work but the bottom line will

Form code

using System;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private TextBoxCreate _textBoxCreator;
        public Form1()
        {
            InitializeComponent();
            _textBoxCreator = new TextBoxCreate() { ParentControl = flowLayoutPanel1 };
        }

        private void createTextBoxButton_Click(object sender, EventArgs e)
        {

            for (var i = 0; i < 10; i++)
            {
                _textBoxCreator.Create();
            }
        }

        private void removeTextboxButton_Click(object sender, EventArgs e)
        {
            _textBoxCreator.RemoveLast();
        }
        private void cmdList_Click(object sender, EventArgs e)
        {
            if (_textBoxCreator.HasItems)
            {
                var result = _textBoxCreator.PopulatedItems();
                Console.WriteLine(result.Count());
            }
        }
    }
}

Class responsible for creating TextBox controls on a FlowLayoutPanel.

using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class TextBoxCreate
    {
        /// <summary>
        /// Storage for TextBoxes
        /// Key is the incrementor for the TextBoxes names
        /// Value is the actual TextBox
        /// </summary>
        public Dictionary<int, TextBox> Items { get; set; }
        public bool HasItems => Items.Count > 0;
        /// <summary>
        /// Parent control where TextBox controls will be placed
        /// </summary>
        public Control ParentControl { get; set; }
        private int _baseHeight = 10;
        private int _textboxWidth = 150;
        private int _indexer = 0;

        public TextBoxCreate()
        {
            Items = new Dictionary<int, TextBox>();
        }
        /// <summary>
        /// Create a single TextBox
        /// </summary>
        public void Create()
        {
            _indexer += 1;
            var tb = new TextBox
            {
                Name = $"txtGenerated{_indexer}",
                Width = _textboxWidth,
                Font = new Font("Arial", 9.75F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0))),
                Location = new Point(25, _baseHeight),
                Parent = ParentControl
            };

            tb.Click += (sender, e) => 
            {
                var currentTextBox = (TextBox)sender;
                // only for demo to show we can subscribe to any event
                MessageBox.Show(currentTextBox.Name); 
            };

            ParentControl.Controls.Add(tb);
            Items.Add(_indexer, tb);
            _baseHeight += 30;
        }

        public List<SelectedItem> PopulatedItems()
        {
            return Items.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Value.Text))
                .Select(kvp => new SelectedItem() {Id = kvp.Key, TextBox = kvp.Value}) 
                .ToList();
        }

        /// <summary>
        /// Remove the last TextBox in the Dictionary
        /// </summary>
        public void RemoveLast()
        {
            if (Items.Count == 0) return;
            var item = Items.Last();
            ParentControl.Controls.Remove(item.Value);
            Items.Remove(item.Key);
        }
    }

    public class SelectedItem
    {
        public int Id { get; set; }
        public TextBox TextBox { get; set; }
    }
}

Tweak the code in the List button


Please remember to mark the replies as answers if they help and unmark 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.
VB Forums - moderator
profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites