C#两个datagridview分别绑定了相同结构的内容不同的DATATABLE,求两个datagridview的横纵滚动条同步滚动
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
参考技术A 在滚动事件里写代码控制另一台dataGridView的滚动条追问
滚动条的坐标位置如何获取?能给出滚动事件的代码吗?
追答private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
dataGridView2.FirstDisplayedScrollingColumnIndex = dataGridView1.FirstDisplayedScrollingColumnIndex;
我试了,但是dataGridView1.FirstDisplayedScrollingColumnIndex永远是“0”啊?这个是为什么?
追答你是横向滚动还是纵向滚动啊
追问横向跟纵向都要!
C# excel文件导入导出
在C#交流群里,看到很多小伙伴在excel数据导入导出到C#界面上存在疑惑,所以今天专门做了这个主题,希望大家有所收获!
环境:win10+vs2017
界面:主要以演示为主,所以没有做优化,然后主界面上添加两个按钮,分别命名为ExportExcel和ImportExcel,添加两个dataGridView,分别是dataGridView1和dataGridView2
然后在窗体加载程序中给dataGridView1写入三行数据,代码如下:
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Age");
dt.Rows.Add("小王","15");
dt.Rows.Add("老李","42");
dt.Rows.Add("老张","25");
dataGridView1.DataSource = dt;
软件运行后,点击ExportExcel,则将datagridview1的数据保存到excel中,点击ImportExcel,选择excel后读取数据到datagridview2.
具体步骤:
step1:引用dll,在nuget上安装Microsoft.Office.Interop.Excel
step2:code
主要由三个方法:
public void ExportExcel() 实现数据导出到excel
public DataSet ImportExcel(int t = 1)实现读取excel数据
public void ExportCSV() 数据导出到csv
其次
保存选项对话框
string fileName = "";
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xlsx";
saveDialog.InitialDirectory = @"C:\BMDT";
saveDialog.Filter = "Excel文件|*.xlsx";
// saveDialog.FileName = fileName;
saveDialog.FileName = "BMDT_Data_" + DateTime.Now.ToLongDateString().ToString();
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0)
{
this.Cursor = Cursors.Default;
return; //被点了取消
}
完整代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Xml;
using System.Data.OleDb;
namespace excelReadWriter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void ExportExcel()
{
try
{
this.Cursor = Cursors.WaitCursor;
if (!Directory.Exists(@"C:\BMDT"))
Directory.CreateDirectory(@"C:\BMDT");
string fileName = "";
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xlsx";
saveDialog.InitialDirectory = @"C:\BMDT";
saveDialog.Filter = "Excel文件|*.xlsx";
// saveDialog.FileName = fileName;
saveDialog.FileName = "BMDT_Data_" + DateTime.Now.ToLongDateString().ToString();
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0)
{
this.Cursor = Cursors.Default;
return; //被点了取消
}
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel");
return;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
Microsoft.Office.Interop.Excel.Range range = worksheet.Range[worksheet.Cells[4, 1], worksheet.Cells[8, 1]];
//写入标题
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{ worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; }
//写入数值
for (int r = 0; r < dataGridView1.Rows.Count; r++)
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
if (this.dataGridView1.Rows[r].Cells[i].Style.BackColor == Color.Red)
{
range = worksheet.Range[worksheet.Cells[r + 2, i + 1], worksheet.Cells[r + 2, i + 1]];
range.Interior.ColorIndex = 10;
}
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
MessageBox.Show(fileName + "资料保存成功", "提示", MessageBoxButtons.OK);
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName); //fileSaved = true;
}
catch (Exception ex)
{//fileSaved = false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//强行销毁
this.Cursor = Cursors.Default;
}
catch(Exception e)
{
this.Cursor = Cursors.Default;
MessageBox.Show(e.ToString());
}
}
public DataSet ImportExcel(int t = 1)
{
//打开文件
string sql_select = string.Empty;
OpenFileDialog file = new OpenFileDialog();
file.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls|(*.csv)|*.csv";
file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
file.Multiselect = false;
if (file.ShowDialog() == DialogResult.Cancel)
return null;
//判断文件后缀
var path = file.FileName;
string fileSuffix = System.IO.Path.GetExtension(path);
if (string.IsNullOrEmpty(fileSuffix))
return null;
using (DataSet ds = new DataSet())
{
//判断Excel文件是2003版本还是2007版本
string connString = "";
if (fileSuffix == ".xls")
connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
//读取文件
if (t == 1)
sql_select = " SELECT ID,CREATETIME,REASONCODE1,PROCESSID FROM [Sheet1$] ";
else if (t == 2)
sql_select = " SELECT PANELID,EVENTTIME,DESCRIPTION,PROCESSID FROM [Grid$] ";
else if (t == 3)
sql_select = " SELECT Operation,Lot_ID,EQP_ID,Event_Time FROM [报表1$] ";
using (OleDbConnection conn = new OleDbConnection(connString))
using (OleDbDataAdapter cmd = new OleDbDataAdapter(sql_select, conn))
{
conn.Open();
cmd.Fill(ds);
}
if (ds == null || ds.Tables.Count <= 0) return null;
return ds;
}
}
private void button1_Click(object sender, EventArgs e)
{
ExportExcel();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Age");
dt.Rows.Add("小王","15");
dt.Rows.Add("老李","42");
dt.Rows.Add("老张","25");
dataGridView1.DataSource = dt;
}
private void button2_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = ImportExcel();
dataGridView2.DataSource = ds.Tables[0];
// ExportCSV();
}
public void ExportCSV()
{
if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.FileName = null;
saveFileDialog.Title = "保存";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Stream stream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
string strLine = "";
try
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i > 0)
strLine += ",";
strLine += dataGridView1.Columns[i].HeaderText;
}
strLine.Remove(strLine.Length - 1);
sw.WriteLine(strLine);
strLine = "";
//表的内容
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
strLine = "";
int colCount = dataGridView1.Columns.Count;
for (int k = 0; k < colCount; k++)
{
if (k > 0 && k < colCount)
strLine += ",";
if (dataGridView1.Rows[j].Cells[k].Value == null)
strLine += "";
else
{
string cell = dataGridView1.Rows[j].Cells[k].Value.ToString().Trim();
//防止里面含有特殊符号
cell = cell.Replace("\"", "\"\"");
cell = "\"" + cell + "\"";
strLine += cell;
}
}
sw.WriteLine(strLine);
}
sw.Close();
stream.Close();
MessageBox.Show("数据被导出到:" + saveFileDialog.FileName.ToString(), "导出完毕", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "导出错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
}
运行效果:
如果你想把数据导入csv文件,则可以用以下方法:
public void ExportCSV()
{
if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.FileName = null;
saveFileDialog.Title = "保存";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Stream stream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
string strLine = "";
try
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i > 0)
strLine += ",";
strLine += dataGridView1.Columns[i].HeaderText;
}
strLine.Remove(strLine.Length - 1);
sw.WriteLine(strLine);
strLine = "";
//表的内容
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
strLine = "";
int colCount = dataGridView1.Columns.Count;
for (int k = 0; k < colCount; k++)
{
if (k > 0 && k < colCount)
strLine += ",";
if (dataGridView1.Rows[j].Cells[k].Value == null)
strLine += "";
else
{
string cell = dataGridView1.Rows[j].Cells[k].Value.ToString().Trim();
//防止里面含有特殊符号
cell = cell.Replace("\"", "\"\"");
cell = "\"" + cell + "\"";
strLine += cell;
}
}
sw.WriteLine(strLine);
}
sw.Close();
stream.Close();
MessageBox.Show("数据被导出到:" + saveFileDialog.FileName.ToString(), "导出完毕", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "导出错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
以上是关于C#两个datagridview分别绑定了相同结构的内容不同的DATATABLE,求两个datagridview的横纵滚动条同步滚动的主要内容,如果未能解决你的问题,请参考以下文章
C#查询出多行数据但只在datagridview中显示其中某一行
c# 中如何把实体类绑定到dataGridView并显示出来。
拜托了各位亲 么么哒 C#中绑定了控件 想往dataGridView中添加一行数据 怎么办???????????急
C# 如何在一个Datagridview 的 某一个cell里面 绑定一个自定义的combobox