代码自己理解一下,注释也很详细了. private void dataGridView1_SelectionChanged(object sender, EventArgs e) { //Get DisplayBandsInfo field var rowBandInfo = typeof(DataGridView).GetField("displayedBandsInfo", BindingFlags.Instance | BindingFlags.NonPublic); if (rowBandInfo != null) { //Get DisplayBandsInfo value var val = rowBandInfo.GetValue(dataGridView1); //Get first and last displayed row index var firstDisplayedScrollingRow = (int)rowBandInfo.FieldType.GetProperty("FirstDisplayedScrollingRow", BindingFlags.Instance | BindingFlags.Public).GetValue(val, null); var lastDisplayedScrollingRow = firstDisplayedScrollingRow + dataGridView1.DisplayedRowCount(false) - 1; if (dataGridView1.CurrentCell != null) { //Get current rows index var currentRowIndex = dataGridView1.CurrentCell.RowIndex; //Get scroll method var scrollMethod = typeof(DataGridView).GetMethod("ScrollRowsByCount", BindingFlags.Instance | BindingFlags.NonPublic); if (scrollMethod != null) { //Use negative value scroll up if (currentRowIndex == firstDisplayedScrollingRow) { scrollMethod.Invoke(dataGridView1, new object[] { -2, ScrollEventType.ThumbPosition }); } //Use positive value scroll down else if (currentRowIndex == lastDisplayedScrollingRow) { scrollMethod.Invoke(dataGridView1, new object[] { 2, ScrollEventType.ThumbPosition }); } } } } }
如果只想滚动一行,修改红色标注的参数 scrollMethod.Invoke(dataGridView1, new object[] { -1, ScrollEventType.ThumbPosition }); scrollMethod.Invoke(dataGridView1, new object[] { 1, ScrollEventType.ThumbPosition });
this.datagridview.FirstDisplayedScrollingRowIndex = datagridview.Rows[X].Index; 竖向滚动位置
{
//Get DisplayBandsInfo field
var rowBandInfo = typeof(DataGridView).GetField("displayedBandsInfo", BindingFlags.Instance | BindingFlags.NonPublic);
if (rowBandInfo != null)
{
//Get DisplayBandsInfo value
var val = rowBandInfo.GetValue(dataGridView1);
//Get first and last displayed row index
var firstDisplayedScrollingRow = (int)rowBandInfo.FieldType.GetProperty("FirstDisplayedScrollingRow", BindingFlags.Instance | BindingFlags.Public).GetValue(val, null);
var lastDisplayedScrollingRow = firstDisplayedScrollingRow + dataGridView1.DisplayedRowCount(false) - 1; if (dataGridView1.CurrentCell != null)
{
//Get current rows index
var currentRowIndex = dataGridView1.CurrentCell.RowIndex;
//Get scroll method
var scrollMethod = typeof(DataGridView).GetMethod("ScrollRowsByCount", BindingFlags.Instance | BindingFlags.NonPublic);
if (scrollMethod != null)
{
//Use negative value scroll up
if (currentRowIndex == firstDisplayedScrollingRow)
{
scrollMethod.Invoke(dataGridView1, new object[] { -2, ScrollEventType.ThumbPosition });
}
//Use positive value scroll down
else if (currentRowIndex == lastDisplayedScrollingRow)
{
scrollMethod.Invoke(dataGridView1, new object[] { 2, ScrollEventType.ThumbPosition });
}
}
}
}
}
scrollMethod.Invoke(dataGridView1, new object[] { -1, ScrollEventType.ThumbPosition });
scrollMethod.Invoke(dataGridView1, new object[] { 1, ScrollEventType.ThumbPosition });