C# synchronize scroll and select of two DataGridViews

2440阅读 0评论2016-06-17 dyli2000
分类:C#/.net

效果图:

同时滚动和选中两个DGV的行。

image

关键代码:


  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Reflection;
  10. namespace SyncDgvs
  11. {
  12.     public partial class Form1 : Form
  13.     {
  14.         public Form1()
  15.         {
  16.             InitializeComponent();
  17.             fillDatagridview();
  18.         }
  19.         private void fillDatagridview()
  20.         {
  21.             dataGridView1.Rows.Clear();
  22.             dataGridView2.Rows.Clear();
  23.             for (int i = 0; i < 100;i++ )
  24.             {
  25.                 dataGridView1.Rows.Add(i,i, i);
  26.                 dataGridView2.Rows.Add(i,i, i);
  27.             }
  28.         }
  29.         private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
  30.         {
  31.             PropertyInfo verticalOffset = dataGridView2.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance);
  32.             verticalOffset.SetValue(this.dataGridView2, dataGridView1.VerticalScrollingOffset, null);
  33.         }
  34.         private void dataGridView2_Scroll(object sender, ScrollEventArgs e)
  35.         {
  36.             PropertyInfo verticalOffset = dataGridView1.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance);
  37.             verticalOffset.SetValue(this.dataGridView1, dataGridView2.VerticalScrollingOffset, null);
  38.         }
  39.         private void dataGridView2_MouseClick(object sender, MouseEventArgs e)
  40.         {
  41.             int iRow = dataGridView2.CurrentRow.Index;
  42.             dataGridView1.ClearSelection();
  43.             dataGridView1.Rows[iRow].Selected = true;
  44.         }
  45.         private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
  46.         {
  47.             int iRow = dataGridView1.CurrentRow.Index;
  48.             dataGridView2.ClearSelection();
  49.             dataGridView2.Rows[iRow].Selected = true;
  50.         }
  51.     }
  52. }


工程代码:

SyncDgvs.rar


参考文献:

上一篇:ImageList+Listview设计图片浏览器
下一篇:List与自定义类的排序一例