none
textbox dynamic to datagridview in windows form and c# RRS feed

  • Question

  • How generate textbox dynamically and send values to a row of a datagridview in windows form and c#

    Monday, December 16, 2019 10:46 PM

All replies

  • Hello,

    To answer your question which is a tad vague but here is how to do adding rows where there are two TextBox and one Button on a panel at the bottom of a form and the DataGridView has two columns.

    And note creating dynamic controls is rare thing to do and requires more code than creating controls at design time.

    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            private IEnumerable<TextBox> _textBoxs;
            public Form1()
            {
                InitializeComponent();
                Shown += Form1_Shown;
            }
    
            private void Form1_Shown(object sender, EventArgs e)
            {
    
                panel1.Controls.Add(new TextBox()
                {
                    Name = "FirstNameTextBox",
                    Top = 10,
                    Left = 30
                });
                panel1.Controls.Add(new TextBox()
                {
                    Name = "LastNameTextBox",
                    Top = 10,
                    Left = 150
                });
                
                var addButton = new Button()
                {
                    Top = 10,
                    Left = 270,
                    Text = "Add"
                };
                addButton.Click += AddButton_Click;
                panel1.Controls.Add(addButton);
            }
    
            private void AddButton_Click(object sender, EventArgs e)
            {
                if (_textBoxs == null)
                {
                    _textBoxs = panel1.Controls.OfType<TextBox>();
                }
    
                var firstNameTextBox = _textBoxs.FirstOrDefault(tb => tb.Name == "FirstNameTextBox");
                var lastNameTextBox = _textBoxs.FirstOrDefault(tb => tb.Name == "LastNameTextBox");
                if (!string.IsNullOrWhiteSpace(firstNameTextBox.Text) || !string.IsNullOrWhiteSpace(lastNameTextBox.Text))
                {
                    dataGridView1.Rows.Add(firstNameTextBox.Text, lastNameTextBox.Text);
                }
    
            }
        }
    }
    

    Or edit a current row

    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            private IEnumerable<TextBox> _textBoxs;
            public Form1()
            {
                InitializeComponent();
                Shown += Form1_Shown;
            }
    
            private void Form1_Shown(object sender, EventArgs e)
            {
    
                panel1.Controls.Add(new TextBox()
                {
                    Name = "FirstNameTextBox",
                    Top = 10,
                    Left = 30
                });
                panel1.Controls.Add(new TextBox()
                {
                    Name = "LastNameTextBox",
                    Top = 10,
                    Left = 150
                });
                
                var addButton = new Button()
                {
                    Top = 10,
                    Left = 270,
                    Text = "Add"
                };
                addButton.Click += AddButton_Click;
                panel1.Controls.Add(addButton);
    
                dataGridView1.Rows.Add("Karen", "Payne");
            }
    
            private void AddButton_Click(object sender, EventArgs e)
            {
                if (_textBoxs == null)
                {
                    _textBoxs = panel1.Controls.OfType<TextBox>();
                }
    
                var firstNameTextBox = _textBoxs.FirstOrDefault(tb => tb.Name == "FirstNameTextBox");
                var lastNameTextBox = _textBoxs.FirstOrDefault(tb => tb.Name == "LastNameTextBox");
                if (!string.IsNullOrWhiteSpace(firstNameTextBox.Text) || !string.IsNullOrWhiteSpace(lastNameTextBox.Text))
                {
                    if (dataGridView1.CurrentRow != null)
                    {
                        dataGridView1.CurrentRow.Cells[0].Value = firstNameTextBox.Text;
                        dataGridView1.CurrentRow.Cells[1].Value = lastNameTextBox.Text;
                    }
                }
    
            }
        }
    }
    
    Hope this leads you in the right direction and note there are ways to to interact between the TextBox controls and the DataGridView without a button but there is a good deal more to this e.g. behavior for instance add a new row per business logic via one event etc.



    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

    Tuesday, December 17, 2019 12:50 AM
    Moderator
  • Thanks  fro answering karen an apology for the vage question. But i need to create the textbox dynamically. I´ve seen different blogs an forums.This is what i take to the moment.

    private void button1_Click(object sender, EventArgs e)
            {
                panel1.Controls.Add(txt);
                txt.Top = cont * 28;
                txt.Left = 15;
                cont = cont + 1;
            }
    
    
    private void button2_Click(object sender, EventArgs e)
            {
               
                //dataGridView1.Rows.Add(txt.Text);
            }

    But just insert in a column

    Tuesday, December 17, 2019 2:17 AM
  • Thanks  fro answering karen an apology for the vage question. But i need to create the textbox dynamically. I´ve seen different blogs an forums.This is what i take to the moment.

    private void button1_Click(object sender, EventArgs e)
            {
                panel1.Controls.Add(txt);
                txt.Top = cont * 28;
                txt.Left = 15;
                cont = cont + 1;
            }
    
    
    private void button2_Click(object sender, EventArgs e)
            {
               
                //dataGridView1.Rows.Add(txt.Text);
            }

    But just insert in a column

    Well I've shown you the very basics to learn from. Other than that you can create a class to create TextBox controls like the following and the click event is simply a demo of doing an event. Other than that I have nothing more other than by reading information from a database to generate controls which can be done with a little effort from my first reply.

    using System.Collections.Generic;
    using System.Drawing;
    using System.Linq;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public class TextBoxCreate
        {
            /// <summary>
            /// Storage for TextBoxes
            /// Key is the increment 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
                };
    
                /*
                 * How to do anonymous events
                 */
                tb.Click += (sender, e) =>
                {
                    var currentTextBox = (TextBox)sender;
                };
    
                ParentControl.Controls.Add(tb);
                Items.Add(_indexer, tb);
                _baseHeight += 30;
            }
            /// <summary>
            /// Get all TextBox controls which have been created
            /// </summary>
            /// <returns></returns>
            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; }
        }
    }
    


    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

    Tuesday, December 17, 2019 3:17 AM
    Moderator