How can I add rows in datafridview in c#.

Total Post:48

Points:336
C# 
C#
 2233  View(s)
Ratings:
Rate this:
Hi,
I am making a program in which I want to add rows in datagridview dynamically. I am also like to add combobox and textbox in cells of datagridview row.

Thanks.
  1. Post:25

    Points:175
    Re: How can I add rows in datagridview in c#.

    Hi Smith,

    You can add rows to the Datagrid using Columns property with Add method. Something like,

    dataGridView1.Rows.Add("Windows XP");

    To add combobox and Textbox to the Cells of the datagrid you can use the Sample code below,

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
     
    namespace BindingTexandCombo
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
     
            private void button1_Click(object sender, EventArgs e)
            {  
                dataGridView1.Columns.Add("Name","Name");            
                var rows = dataGridView1.Rows;
     
                rows.Add("Suhash");
                rows.Add("Lithi");
                rows.Add("Chintu");
     
                DataGridViewColumn particulars = new DataGridViewTextBoxColumn();
                particulars.HeaderText = "Place";
                particulars.Name = "Place";
                dataGridView1.Columns.Add(particulars);
     
                DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
                cmb.Name = "Gender";
                cmb.Name = "Gender";
                cmb.Items.Add("Male");
                cmb.Items.Add("Female");
                dataGridView1.Columns.Add(cmb);
            }
     
            private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
            {
                //Create and fill a list to use as the custom data source
                var source = new AutoCompleteStringCollection();
                source.AddRange(new string[] { "Chennai", "Thiruvallur", });
     
                //Set the appropriate properties on the textbox control
                TextBox dgvEditBox = e.Control as TextBox;
                if (dgvEditBox != null)
                {
                    dgvEditBox.AutoCompleteMode = AutoCompleteMode.Suggest;
                    dgvEditBox.AutoCompleteCustomSource = source;
                    dgvEditBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
                }
            }
        }
    }

     Hope this might help you.

    Thanks,

    Shankar

      Modified On Mar-29-2018 06:25:16 AM

Answer