效果图:
同时滚动和选中两个DGV的行。
关键代码:
-
using System;
-
using System.Collections.Generic;
-
using System.ComponentModel;
-
using System.Data;
-
using System.Drawing;
-
using System.Linq;
-
using System.Text;
-
using System.Windows.Forms;
-
using System.Reflection;
-
namespace SyncDgvs
-
{
-
public partial class Form1 : Form
-
{
-
public Form1()
-
{
-
InitializeComponent();
-
fillDatagridview();
-
}
-
private void fillDatagridview()
-
{
-
dataGridView1.Rows.Clear();
-
dataGridView2.Rows.Clear();
-
for (int i = 0; i < 100;i++ )
-
{
-
dataGridView1.Rows.Add(i,i, i);
-
dataGridView2.Rows.Add(i,i, i);
-
}
-
}
-
private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
-
{
-
PropertyInfo verticalOffset = dataGridView2.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance);
-
verticalOffset.SetValue(this.dataGridView2, dataGridView1.VerticalScrollingOffset, null);
-
}
-
private void dataGridView2_Scroll(object sender, ScrollEventArgs e)
-
{
-
PropertyInfo verticalOffset = dataGridView1.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance);
-
verticalOffset.SetValue(this.dataGridView1, dataGridView2.VerticalScrollingOffset, null);
-
}
-
private void dataGridView2_MouseClick(object sender, MouseEventArgs e)
-
{
-
int iRow = dataGridView2.CurrentRow.Index;
-
dataGridView1.ClearSelection();
-
dataGridView1.Rows[iRow].Selected = true;
-
}
-
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
-
{
-
int iRow = dataGridView1.CurrentRow.Index;
-
dataGridView2.ClearSelection();
-
dataGridView2.Rows[iRow].Selected = true;
-
}
-
}
- }
工程代码:
参考文献: