I have a vertically and horizontally scrollable DataGridView on a form.
I use virtual mode because the underlying datatable is huge.
When I scroll right, if the last column is not fully shown in the view, then I see repeated calls to CellValueNeeded.
How can I fix this?
My thoughts:
Why is CellValueNeed being repeatedly called for a partially visible column anyway? Perhaps I can fix the cause of this.
Within CelValueNeeded - can I detect it is partially visible and return without processing? Both "Displayed" and "Visible" are true when I check the cell values.
My code:
private void grid_Data_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
Console.WriteLine("CellValue: " + e.RowIndex + " " + e.ColumnIndex);
if (e.RowIndex > Grid.Rows.Count - 1)
return;
DataGridView gridView = sender as DataGridView;
e.Value = Grid.Rows[e.RowIndex][e.ColumnIndex];
gridView.Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex).ToString();
}
EDIT1:
After Digitalsa1nt's answer I found a way to fix the issue. It is complicated because the first column is treated differently to the last column. AND it makes a difference if you are setting RowHeaders.
In CellValueNeed above, I now return if the following function is true.
private bool IsPartiallyVisible(DataGridView gridView, DataGridViewCellValueEventArgs e)
{
if (gridView.FirstDisplayedScrollingColumnIndex == e.ColumnIndex)
{
if (gridView.FirstDisplayedScrollingColumnHiddenWidth != 0)
{
return true;
}
}
bool sameWidth = gridView.GetColumnDisplayRectangle(e.ColumnIndex, false).Width == gridView.GetColumnDisplayRectangle(e.ColumnIndex, true).Width;
return !sameWidth;
}