C#两个datagridview分别绑定了相同结构的内容不同的DATATABLE,求两个datagridview的横纵滚动条同步滚动
展开全部
这么写就行了
类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
namespace Test
{
public class DataGridViewEx : DataGridView
{
private Type type = typeof(DataGridViewEx);
private PropertyInfo horPropertyInfo;
private PropertyInfo verPropertyInfo;
public DataGridViewEx ScrollDataGridViewEx { get; set; }
public new ScrollBar VerticalScrollBar
{
get
{
return base.VerticalScrollBar;
}
}
public new ScrollBar HorizontalScrollBar
{
get
{
return base.HorizontalScrollBar;
}
}
public DataGridViewEx()
{
horPropertyInfo = type.GetProperty("HorizontalOffset", BindingFlags.NonPublic | BindingFlags.Instance);
verPropertyInfo = type.GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance);
}
protected override void OnScroll(ScrollEventArgs e)
{
if (ScrollDataGridViewEx != null)
{
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll &&
ScrollDataGridViewEx.HorizontalScrollBar.Visible)
{
ScrollDataGridViewEx.HorizontalScrollBar.Value = this.HorizontalScrollBar.Value;
horPropertyInfo.SetValue(ScrollDataGridViewEx, this.HorizontalScrollBar.Value, null);
}
if (e.ScrollOrientation == ScrollOrientation.VerticalScroll &&
ScrollDataGridViewEx.VerticalScrollBar.Visible)
{
ScrollDataGridViewEx.VerticalScrollBar.Value = this.VerticalScrollBar.Value;
verPropertyInfo.SetValue(ScrollDataGridViewEx, this.VerticalScrollBar.Value, null);
}
}
base.OnScroll(e);
}
}
}
使用:
private void Form1_Load(object sender, EventArgs e)
{
dataGridViewEx1.ScrollDataGridViewEx = dataGridViewEx2;
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("A"));
dt.Columns.Add(new DataColumn("B"));
dt.Columns.Add(new DataColumn("C"));
dt.Columns.Add(new DataColumn("D"));
DataTable dt2 = dt.Clone();
for (int i = 0; i < 20; i++)
{
dt.Rows.Add(i, i + 1, i + 2, i + 3);
dt2.Rows.Add(i, i + 10, i + 20, i + 30);
}
dataGridViewEx1.DataSource = dt;
dataGridViewEx2.DataSource = dt2;
}
展开全部
在滚动事件里写代码控制另一台dataGridView的滚动条
更多追问追答
追问
滚动条的坐标位置如何获取?能给出滚动事件的代码吗?
追答
private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
dataGridView2.FirstDisplayedScrollingColumnIndex = dataGridView1.FirstDisplayedScrollingColumnIndex;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询