MrDysprosium MrDysprosium - 2 months ago 15
C# Question

Which override in Winforms will trigger when data is added to a grid's itemsource?

I currently use

Onload(EventArgs e)
to fire a function that will iterate over my data and change colors of cells based on value, but when I add data to the DataGridView's itemsource I'm not sure how to call this same function.

Is there an override to satisfy this case?

Example of what I currently use for
OnLoad
:

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
PaintSquares();
}

Answer

You don't need to iterate between rows and cells to format them, it's enough to use CellFormatting event of DataGridView:

void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex < 0 || e.RowIndex < 0)
        return;

    if (string.Format("{0}", e.Value) == "OK")
    {
        e.CellStyle.BackColor = Color.Red;
    }
}

If for any reason you want to use some change events, ListChanged event of the data source is suitable event for detecting occurrence of a change. BindingSource and BindingList<T> (which you are using - based on your previous question) both have ListChanged event.

Also you can rely on DataGridView events like RowsAdded, RowsRemoved and CellValueChanged.