[c#] How to add a new row to datagridview programmatically

if add row to DataTable

DataRow row = datatable1.NewRow();
row["column2"]="column2";
row["column6"]="column6";
datatable1.Rows.Add(row);

How about DataGridView??

This question is related to c# winforms datagridview row

The answer is


If you are binding a List

List<Student> student = new List<Student>();

dataGridView1.DataSource = student.ToList();
student .Add(new Student());

//Reset the Datasource
dataGridView1.DataSource = null;
dataGridView1.DataSource = student;

If you are binding DataTable

DataTable table = new DataTable();

 DataRow newRow = table.NewRow();

// Add the row to the rows collection.
table.Rows.Add(newRow);

Like this:

var index = dgv.Rows.Add();
dgv.Rows[index].Cells["Column1"].Value = "Column1";
dgv.Rows[index].Cells["Column2"].Value = 5.6;
//....

An example of copy row from dataGridView and added a new row in The same dataGridView:

DataTable Dt = new DataTable();
Dt.Columns.Add("Column1");
Dt.Columns.Add("Column2");

DataRow dr = Dt.NewRow();
DataGridViewRow dgvR = (DataGridViewRow)dataGridView1.CurrentRow;
dr[0] = dgvR.Cells[0].Value; 
dr[1] = dgvR.Cells[1].Value;              

Dt.Rows.Add(dR);
dataGridView1.DataSource = Dt;

Like this:

 dataGridView1.Columns[0].Name = "column2";
 dataGridView1.Columns[1].Name = "column6";

 string[] row1 = new string[] { "column2 value", "column6 value" };
 dataGridView1.Rows.Add(row1);

Or you need to set there values individually use the propery .Rows(), like this:

 dataGridView1.Rows[1].Cells[0].Value = "cell value";

Lets say you have a datagridview that is not bound to a dataset and you want to programmatically populate new rows...

Here's how you do it.

// Create a new row first as it will include the columns you've created at design-time.

int rowId = dataGridView1.Rows.Add();

// Grab the new row!
DataGridViewRow row = dataGridView1.Rows[rowId];

// Add the data
row.Cells["Column1"].Value = "Value1";
row.Cells["Column2"].Value = "Value2";

// And that's it! Quick and painless... :o)

If you need to manipulate anything aside from the Cell Value string such as adding a Tag, try this:

DataGridViewRow newRow = (DataGridViewRow)mappingDataGridView.RowTemplate.Clone();
newRow.CreateCells(mappingDataGridView);

newRow.Cells[0].Value = mapping.Key;
newRow.Cells[1].Value = ((BusinessObject)mapping.Value).Name;
newRow.Cells[1].Tag = mapping.Value;

mappingDataGridView.Rows.Add(newRow);

If the grid is bound against a DataSet / table its better to use a BindingSource like

var bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
grid.DataSource = bindingSource;

//Add data to dataTable and then call

bindingSource.ResetBindings(false)    

This is how I add a row if the dgrview is empty: (myDataGridView has two columns in my example)

DataGridViewRow row = new DataGridViewRow();
row.CreateCells(myDataGridView);

row.Cells[0].Value = "some value";
row.Cells[1].Value = "next columns value";

myDataGridView.Rows.Add(row);

According to docs: "CreateCells() clears the existing cells and sets their template according to the supplied DataGridView template".


//Add a list of BBDD
var item = myEntities.getList().ToList();
//Insert a new object of type in a position of the list       
item.Insert(0,(new Model.getList_Result { id = 0, name = "Coca Cola" }));

//List assigned to DataGridView
dgList.DataSource = item; 

I have found this useful more than once when the DataGrid is bound to a table.

        DataTable dt = (DataTable)dgvData.DataSource;
        DataRow row = dt.NewRow();
        foreach (var something in something)
        {
           row["ColumnName"] = something ;               
        }
        dt.Rows.Add(row);
        dgvData.DataSource = dt;

//header
dataGridView1.RowCount = 50;
dataGridView1.Rows[0].HeaderCell.Value = "Product_ID0";


//add row by cell 
 dataGridView1.Rows[1].Cells[0].Value = "cell value";

string[] splited = t.Split('>');
int index = dgv_customers.Rows.Add(new DataGridViewRow());
dgv_customers.Rows[index].Cells["cust_id"].Value=splited.WhichIsType("id;");

But be aware, WhichIsType is the extension method I created.


yourDGV.Rows.Add(column1,column2...columnx); //add a row to a dataGridview
yourDGV.Rows[rowindex].Cells[Cell/Columnindex].value = yourvalue; //edit the value

you can also create a new row and then add it to the DataGridView like this:

DataGridViewRow row = new DataGridViewRow();
row.Cells[Cell/Columnindex].Value = yourvalue;
yourDGV.Rows.Add(row);

Adding a new row in a DGV with no rows with Add() raises SelectionChanged event before you can insert any data (or bind an object in Tag property).

Create a clone row from RowTemplate is safer imho:

//assuming that you created columns (via code or designer) in myDGV
DataGridViewRow row = (DataGridViewRow) myDGV.RowTemplate.Clone();
row.CreateCells(myDGV, "cell1", "cell2", "cell3");

myDGV.Rows.Add(row);

here is another way to do such

 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        dataGridView1.ColumnCount = 3;

        dataGridView1.Columns[0].Name = "Name";
        dataGridView1.Columns[1].Name = "Age";
        dataGridView1.Columns[2].Name = "City";

        dataGridView1.Rows.Add("kathir", "25", "salem");
        dataGridView1.Rows.Add("vino", "24", "attur");
        dataGridView1.Rows.Add("maruthi", "26", "dharmapuri");
        dataGridView1.Rows.Add("arun", "27", "chennai"); 
    }

Consider a Windows Application and using Button Click Event put this code in it.

dataGridView1.Rows
                .Add(new object[] { textBox1.Text, textBox2.Text, textBox3.Text });

If you´ve already defined a DataSource, You can get the DataGridView´s DataSource and cast it as a Datatable.

Then add a new DataRow and set the Fields Values.

Add the new row to the DataTable and Accept the changes.

In C# it would be something like this..

DataTable dataTable = (DataTable)dataGridView.DataSource;
DataRow drToAdd = dataTable.NewRow();

drToAdd["Field1"] = "Value1";
drToAdd["Field2"] = "Value2";

dataTable.Rows.Add(drToAdd);
dataTable.AcceptChanges();

If anyone wanted to Add DataTable as a source of gridview then--

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("column1"));
dt.Columns.Add(new DataColumn("column2"));

DataRow dr = dt.NewRow();
dr[0] = "column1 Value";
dr[1] = "column2 Value";

dt.Rows.Add(dr);

dataGridView1.DataSource = dt;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results

Examples related to row

Python Pandas Replacing Header with Top Row Return row number(s) for a particular value in a column in a dataframe How to insert a row in an HTML table body in JavaScript Referencing Row Number in R Python pandas: fill a dataframe row by row MS SQL 2008 - get all table names and their row counts in a DB How do I delete rows in a data frame? Remove table row after clicking table row delete button Javascript get the text value of a column from a particular row of an html table How to add a new row to datagridview programmatically