我有一个表单,其中一些控件根据 DataGridView 中当前显示的行(及其位置)进行更新。因此,在dataGridView1.VerticalScrollBar.ValueChanged
事件中,我遍历所有行并检查它们是否显示。
所以这是滚动回顶部(通过鼠标滚轮)时的问题:
dataGridView1.VerticalScrollBar.Value
是0
-> 好的dataGridView1.FirstDisplayedCell.RowIndex
是0
-> 好的dataGridView1.FirstDisplayedScrollingRowIndex
是0
-> 好的dataGridView1.Rows[0].Displayed
仍然false
-> 嗯?dataGridView1.GetRowDisplayRectangle(0, false)
也是{0,0,0,0}
-> ...?
检查https://referencesource.microsoft.com后,我意识到FirstDisplayedCell
实际使用this.Rows.GetFirstRow(DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen)
,这似乎有点不正确,还是我错了?我该如何解决这个问题,以便获得第一行的正确显示信息/矩形?
先感谢您!
代码:
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);
}
}