break

C#: Datagridviewcell value not displayed

I was trying to add a value to a specific DataGridViewCell. To accomplish these you need to do something like this:

DataGridViewCell cellLotsOfAmount = monitorDataGrid[e.ColumnIndex, e.RowIndex];
cellLotsOfAmount.Value = lotsOfAmount;

This should do the work; however, there may be the case ( as it was happening to me ) that you are doing this inside a method, and for some reason, the value is not being displayed in the DataGridViewCell. I tried lots of things inside this method, that didn’t quite work for me.
If you search around different users will probably suggest to
- Invalidate the cell: monitorDataGrid.InvalidateCell(cell);
- Refresh edit the datagridview: monitorDataGrid.RefreshEdit();
etc,etc,etc

However, what actually worked for me, was to change the value of the cell inside the DataGridView.CellFormatting event. According to the MSDN library this occurs “when the contents of a cell need to be formatted for display.”

My code inside this event looks something like this:

private void monitorDataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// search for the column you are looking for
if (monitorDataGrid.Columns[e.ColumnIndex].HeaderText == "Lots of amount")
{
// get the cell you are looking for
DataGridViewCell cellLotsOfAmount = monitorDataGrid[e.ColumnIndex, e.RowIndex];
// change the value
cellLotsOfAmount.Value = lotsOfAmount;
}
}

Doing this I didn’t have invalidate or refresh the datagridview in order for my value to be displayed. This is how I solved this problem, if this helped you to solve it, or you have a different thought on this, I’ll be glad to know about it.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

CAPTCHA Image
Reload Image