I have a Form where some Controls update according to the current displayed Rows (and their positions) in a DataGridView. So inside the dataGridView1.VerticalScrollBar.ValueChanged
event I iterate through all rows and check wether they are displayed or not.
So here's the issue when scrolling back to top (by mousewheel):
dataGridView1.VerticalScrollBar.Value
is0
-> OKdataGridView1.FirstDisplayedCell.RowIndex
is0
-> OKdataGridView1.FirstDisplayedScrollingRowIndex
is0
-> OKdataGridView1.Rows[0].Displayed
is stillfalse
-> huh?dataGridView1.GetRowDisplayRectangle(0, false)
is also{0,0,0,0}
-> ...?
After checking https://referencesource.microsoft.com, I realized that FirstDisplayedCell
actually uses this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)
, which seems kind of incorrect, or am I wrong?
How do I fix this, so that I get the correct displayed information / rectangle of the first row?
Thank you in advance!
Code:
public partial class Form1 : Form
{
private List<Person> persons = new List<Person>()
{
{new Person("mike", 20) },
{new Person("tim", 31) },
{new Person("steven", 15) },
{new Person("dave", 41) },
{new Person("tom", 35) },
{new Person("bob", 18) },
{new Person("peter", 22) },
{new Person("sarah", 55) },
{new Person("robert", 69) },
{new Person("andre", 23) },
};
public Form1()
{
this.InitializeComponent();
this.dataGridView1.DataSource = new BindingSource(this.persons, null);
if (typeof(DataGridView).GetProperty("VerticalScrollBar", BindingFlags.Instance | BindingFlags.NonPublic) is PropertyInfo pi &&
pi.GetValue(this.dataGridView1, null) is ScrollBar sb)
{
sb.ValueChanged += this.Sb_ValueChanged;
}
}
private void Sb_ValueChanged(object sender, EventArgs e)
{
int scrollValue = (sender as ScrollBar).Value;
int index = this.dataGridView1.FirstDisplayedCell.RowIndex;
int index2 = this.dataGridView1.FirstDisplayedScrollingRowIndex;
DataGridViewRow row = this.dataGridView1.Rows[index];
bool displayed = row.Displayed;
Rectangle rect = this.dataGridView1.GetRowDisplayRectangle(index, false);
}
}