Select New Added Row - DataGridView and BindingSource

I am adding a new row to a BindingSource bound to a DataGridView

source.AddNew(); 

After that, use BindingSource to get the added row, returning the next row to the DataGridView when sorting it.

 ROW "A" ROW "B" <- myBindingSource.AddNew(); ROW "C" 

myBindingSource.Current gives a ROW of "C". (it became the selected row in the DataGridView)

I need this because I want to update only the added row

  DataRowView drv = (DataRowView)myBindingSource.Current; myTableAdapter.Update(drv.Row); 

not the whole table.

  myTableAdapter.Update(myDataSet.myTable); 

and also, I would like this new added row to be selected in the DataGridView after insertion.

Is this possible somehow?

+4
source share
5 answers

I donโ€™t know how to determine its best solution, but, for example, it looks better than iteration.

  DataRowView drv = (DataRowView)source.AddNew(); grupoTableAdapter.Update(drv.Row); grupoBindingSource.Position = grupoBindingSource.Find("ID", drv.Row.ItemArray[0]); 
+1
source

Use events from the DataGridView, like this for this task:

 private void RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) { this.Rows[e.RowIndex].Selected = true; } 

This marks the added row as selected.

+7
source

Is it possible? I would say yes .

Here's a related article:
DataGridView and BindingSource (at the Joel Forum)

+1
source

You have already identified one way to achieve this. Another way to achieve this is to completely ignore the interface:

 foreach (DataRow r in myTable.AsEnumerable().Where(x => x.RowState == DataRowState.Added)) { myTableAdapter.Update(r); } 

Of course, this causes Update in all the added rows in the table, and not in what was just added, so if you have some crazy script where you have two different ways to add new rows to the table, that works.

0
source

Responding to Oliver Friedrichโ€™s answer, a function created using the property of controls, as shown in the constructor, will look like this:

 private void drv_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) { drv.Rows[e.RowIndex].Selected = true; } 
0
source

All Articles