if add row to DataTable
DataRow row = datatable1.NewRow();
row[\"column2\"]=\"column2\";
row[\"column6\"]=\"column6\";
datatable1.Rows.Add(row);
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);
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);
//header
dataGridView1.RowCount = 50;
dataGridView1.Rows[0].HeaderCell.Value = "Product_ID0";
//add row by cell
dataGridView1.Rows[1].Cells[0].Value = "cell value";
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)
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.
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;