How to programmatically set cell value in DataGridView?

XXXXX picture XXXXX · Oct 4, 2009 · Viewed 233.3k times · Source

I have a DataGridView. Some of the cells receive their data from a serial port: I want to shove the data into the cell, and have it update the underlying bound object.

I'm trying something like this:

SetValueFromSerial (decimal newValue)
{
    dataGridView.CurrentCell.Value = newValue;
}

using a string doesn't help:

    dataGridView.CurrentCell.Value = newValue.ToString ();

In both cases, I don't see anything in the grid, and the underlying value is unchanged.

I did Google and search here, but I didn't find anything. (I may have missed something, perhaps something obvious, but I'm not utterly lazy.)

Answer

Thomas Levesque picture Thomas Levesque · Oct 4, 2009

If the DataGridView is databound, you shouldn't directly modify the content of the cell. Instead, you should modify the databound object. You can access that object through the DataBoundItem of the DataGridViewRow :

MyObject obj = (MyObject)dataGridView.CurrentRow.DataBoundItem;
obj.MyProperty = newValue;

Note that the bound object should implement INotifyPropertyChanged so that the change is reflected in the DataGridView