NickSharp
NickSharp

Reputation: 281

How to programmatically add a row to a datagridview when it is data-bound?

How can I add a row to a datagridview control if it is bounded to a datasource (datatable) ? Thanks!

Upvotes: 12

Views: 15743

Answers (4)

user13028588
user13028588

Reputation:

I used dataset to add row to the datagridview if I try to add rows to the datagridview itself it says that it does not excepts adding rows programaticly because its databound.

// DataSet of the datagridview can be found in the Form Load

advokathusetDataSet.Kunde.Rows.Add(DeletedRowsList[lastindex].Cells[0].Value, DeletedRowsList[lastindex].Cells[1].Value, DeletedRowsList[lastindex].Cells[2].Value, DeletedRowsList[lastindex].Cells[3].Value, DeletedRowsList[lastindex].Cells[4].Value, DeletedRowsList[lastindex].Cells[5].Value, DeletedRowsList[lastindex].Cells[6].Value);

// Add row from Datagridview to list and Add row to datagridview from list - How to add row to datagridview using list

Upvotes: 0

CW1255
CW1255

Reputation: 121

// I manipulated a binding list. Here I was moving a row down in sequence.

BindingList<MyType> lst = (BindingList<MyType>)DataGridView.DataSource;
MyType objQcc = lst[rowIndex];
lst.Insert(rowIndex + 2, objQcc);
lst.RemoveAt(rowIndex);        

Upvotes: 0

Avi Turner
Avi Turner

Reputation: 10466

Add a row to the datatable, the datagridview will update automatically:

DataTable dt = myDataGridView.DataSource as DataTable;
//Create the new row
DataRow row = dt.NewRow();

//Populate the row with data

//Add the row to data table
dt.Rows.Add(row);

Upvotes: 20

MPelletier
MPelletier

Reputation: 16657

  • Create a class that corresponds to the data you want to display in your grid (same properties)
  • In your data-binding function, get your query result, but put the result in a list (or any IEnumerable that suits you and the data binding)
  • Create and add another object to your list according to your needs
  • Bind the list

Upvotes: 0

Related Questions