3

I'm looking for some advice on the most efficient way of changing the cell value of each row within a DataGridView. I think that there could possibly be different ways of achieving this but I don't want to start coding it without some advice and end up going down the wrong route.

The value would always be in the same column, would it be possible to loop through each row in the DGV using a foreach loop, read the data within the row on the correct column and simply use something like row[columnIndex] = "x value"; Or would I be better off taking all of the DGV data and putting it into a Datatable, updating the data and then reapplying it to the DataGridView.

Thanks

Paul Alexander
  • 2,686
  • 4
  • 33
  • 69
  • You do not specify how the `DataGridView` is initially filled? If it currently has a `DataSource` then you would want to use it. If the grid is not data bound then @Ikram Turgunbaev's solution is the way to go once you have a `DataTable`. Loop through the rows and make a `DataTable` if necessary. – JohnG Feb 03 '17 at 11:14
  • _I don't want to start coding it without some advice and end up going down the wrong route_ - wrong approach. Only you know "actual" context of your application - start with something - then read advises. Without doing anything you didn't understand advises – Fabio Feb 03 '17 at 14:46
  • Note you can address the cells `dgv1(colIndex,rowIndex)` I think you may be looking for 'elegant' rather than 'efficient' - unless you have a very large amount of data. – rheitzman Feb 03 '17 at 15:40

1 Answers1

4

In my case it would be using bindingsource

using bindingsource every change on source will effect on control, and every change on control will effect on source

DataTable dt = GetTable();
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;

foreach(DataRow row in dt.Rows)
{
   row.BeginEdit();
   row.["SomeColumn"] = somevalue;
   row.EndEdit();
}
kgzdev
  • 2,770
  • 2
  • 18
  • 35
  • And is this more efficient than `foreach(DataGridViewRow row in DataGridView1.Rows)..` ? – Pikoh Feb 03 '17 at 11:05
  • In his case he said "Or would I be better off taking all of the DGV data and putting it into a Datatable, updating the data and then reapplying it to the DataGridView.". So I think using bindingsource is more efficient – kgzdev Feb 03 '17 at 11:09
  • Why use the binding source? Wouldn't using the datatable (or a derived dataview) work the same for the OP? A bindingsource is certainly more powerful https://msdn.microsoft.com/en-us/library/xxxf124e(v=vs.110).aspx – rheitzman Feb 03 '17 at 15:47