185

if add row to DataTable

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

How about DataGridView??

Habib
  • 219,104
  • 29
  • 407
  • 436
LK Yeung
  • 3,462
  • 5
  • 26
  • 39
  • 3
    You can add the data of a datatable to a datagridview just by setting the datasource of the gridview equal to the datatable `datagridview1.DataSource = yourDataTable` – Jonathan Van Dam Aug 14 '16 at 23:16

20 Answers20

297

You can do:

DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells[0].Value = "XYZ";
row.Cells[1].Value = 50.2;
yourDataGridView.Rows.Add(row);

or:

DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells["Column2"].Value = "XYZ";
row.Cells["Column6"].Value = 50.2;
yourDataGridView.Rows.Add(row);

Another way:

this.dataGridView1.Rows.Add("five", "six", "seven","eight");
this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");

From: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rows.aspx

Habib
  • 219,104
  • 29
  • 407
  • 436
  • 40
    thank you, if my datagridview have no rows, how can i add row? – LK Yeung Apr 08 '12 at 15:16
  • 3
    @DavidYeung well in that case answer from MGA can help you out, what is your data source ? is it a datatable? if so you can add the row to the datatable and then refresh the data source – Habib Apr 08 '12 at 15:19
  • 8
    You cannot directly reference a column by name as you did: row.Cells["Column2"].Value = "XYZ"; ... You have to look up the index first: row.Cells[yourDataGridView.Columns["Column2"].Index].Value = "XYZ"; – Tizz Dec 03 '12 at 19:55
  • 4
    Ideally, you should clone the `RowTemplate` of the `DataGridView`. This becomes more of an issue when you have different styles across different rows in the `DataGridView`. – Anthony Sep 17 '13 at 16:42
  • Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound. – Darth Sucuk Oct 02 '18 at 14:23
  • when it bided to data it will get error. – AliNajafZadeh Nov 23 '21 at 10:40
65

Like this:

var index = dgv.Rows.Add();
dgv.Rows[index].Cells["Column1"].Value = "Column1";
dgv.Rows[index].Cells["Column2"].Value = 5.6;
//....
Jizakh
  • 651
  • 5
  • 2
  • Thanks, this works really well if you have a simple single column DataGridView for simple editable lists of text. – Bob Moss Dec 06 '13 at 16:21
  • Its works great in the case when you have no data source assigned to grid view – Jhabar Sep 23 '18 at 12:51
  • Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound. – Darth Sucuk Oct 02 '18 at 14:23
  • And **can be easily cleared** (in case of showing new result/refreshing search data etc.) with **`datagridview1.Rows.Clear();`** – Shahaboddin Mar 21 '22 at 04:42
56

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)
Overdrive77
  • 561
  • 4
  • 2
35

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";
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
  • 1
    thank you. if the datagridview have 30 columns, but i just want to add the value to column2 and column6 and the rest keep null or empty . how can i do this?? – LK Yeung Apr 08 '12 at 15:10
  • 1
    @DavidYeung, Sure you can: `dataGridView1.Rows[1].Cells[0].Value = "cell value"`; – Mahmoud Gamal Apr 08 '12 at 15:15
  • 1
    dataGridView.Rows.Add(null, 2, null, null, null, 6); – MrFox Nov 09 '12 at 15:39
  • int addedRowIndex = dataGridViewRows.Add(); var addedRow = dataGridViewRows[addedRowIndex]; now all values are filled with the default value, you only have to change the cells that are not default: addedRow.Cells[column2.Index].Value = myValue; (assuming column2 is a DataGridViewColumn) – Harald Coppoolse Mar 30 '17 at 13:22
29

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);
Defkon1
  • 492
  • 4
  • 15
16

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".

Tornseglare
  • 963
  • 1
  • 11
  • 24
8

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)    
Anders
  • 17,306
  • 10
  • 76
  • 144
7

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"); 
    }
RC-AI
  • 114
  • 1
  • 12
7

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);
5

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);
silent tone
  • 539
  • 7
  • 12
3
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);
F.joksch
  • 132
  • 1
  • 6
2

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;
AbdusSalam
  • 420
  • 6
  • 10
1

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;
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Sherif Hamdy
  • 587
  • 6
  • 10
1

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 });
DotNET
  • 55
  • 8
1
//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; 
Rei Salazar
  • 101
  • 1
  • 3
  • 3
1

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();
Ali
  • 3,373
  • 5
  • 42
  • 54
luchezco
  • 221
  • 2
  • 2
1
//header
dataGridView1.RowCount = 50;
dataGridView1.Rows[0].HeaderCell.Value = "Product_ID0";


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

I think the cleanest way to do is invoking the DataGridView and using a lambda expression. Simple one liner while also keeping the code thread safe:

MyDataGridView.Invoke((MethodInvoker)(() => MyDataGridView.Rows.Add(param1, param2, paramX)));
0

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;
Alex M
  • 141
  • 2
  • 6
-1
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.

Fabian Schultz
  • 18,138
  • 5
  • 49
  • 56
rangeeeer
  • 9
  • 1
  • 2
    When you answer a question with some code, and that code requires a custom extension method you created, and you didn't include the code for the custom method, it isn't a terribly useful answer. – Bryan Jan 03 '17 at 23:04
  • thanks for the tip. i am sory becuse of that. but that methode its not an important methode – rangeeeer Jan 04 '17 at 10:51