最近做项目时,显示查询结果总需要绑定到datagridview控件上显示,总结了给datagridview绑定数据的方式,以及导出datagridview数据到excel表格,如有错误请多指教

1.直接绑定数据源,可以绑定的数据格式有List<T>,DataTable,DataSet等,

this.dataGridView1.DataSource = list;

this.dataGridView1.DataSource = table;

this.dataGridView1.DataSource =ds.Tables["表名"];

2.手动绑定datagridview指定列的数据,datagridview列如下图:

绑定数据代码如下:

DataTable dt = cdh.checkDB_typeValue(list_rd);
if (dt.Rows.Count>)
{
//dataGridView2.DataSource = dt;
for (int i = ; i < dt.Rows.Count; i++)
{
DataGridViewRow dr = new DataGridViewRow();
dataGridView2.Rows.Add(dr);
dataGridView2.Rows[i].Cells["档案类型"].Value = dt.Rows[i]["档案类型"].ToString();
dataGridView2.Rows[i].Cells["字段"].Value = dt.Rows[i]["字段"].ToString();
dataGridView2.Rows[i].Cells["错误类型"].Value = dt.Rows[i]["错误类型"].ToString();
dataGridView2.Rows[i].Cells["错误数据"].Value = dt.Rows[i]["错误数据"].ToString();
dataGridView2.Rows[i].Cells["档案号"].Value = dt.Rows[i]["档案号"].ToString();
}
btn_export.Enabled = true;
}

绑定datagridview数据

3.自动生成datagridview控件并绑定数据和单元格点击事件

foreach (KeyValuePair<string, List<string>> item in ckImageMethod.errorFiles)
{
//实例化tabpage对象
TabPage tpage = new TabPage(); tpage.Text = item.Key;
tpage.AutoScroll = true;
//实例化datagridview对象
DataGridView dgv = new DataGridView();
dgv.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
dgv.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
dgv.Location = new System.Drawing.Point(, );
dgv.Size = new System.Drawing.Size(tabControl2.Width - , tabControl2.Height - );
//给datagridview添加单元格点击事件
dgv.CellContentClick += Dgv_CellContentClick;
//给datagridview添加文本列
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
col1.HeaderText = "文件名";
DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
col2.HeaderText = "文件路径";
//添加按钮列
DataGridViewButtonColumn col3 = new DataGridViewButtonColumn();
col3.HeaderText = "操作";
col3.Name = "btnModify";
col3.DefaultCellStyle.NullValue = "打开文件";
dgv.Columns.Add(col1);
dgv.Columns.Add(col2);
dgv.Columns.Add(col3); foreach (string filePath in item.Value)
{
string path = filePath;
//给datagridview添加一行数据,因为第三列时按钮,所以不添加值也会默认添加按钮
dgv.Rows.Add(path.Substring(path.LastIndexOf('\\') + ), path);
}
//添加datagridview控件到tabpage中
tpage.Controls.Add(dgv);
//添加tabpage到tabControl中
tabControl2.TabPages.Add(tpage);
}

后台添加datagridview控件并绑定数据

单元格点击事件:

private void Dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = sender as DataGridView;
//点击button按钮事件
if (dgv.Columns[e.ColumnIndex].Name == "btnModify" && e.RowIndex >= )
{
if (e.RowIndex == (dgv.RowCount - ))
{
return;
}
//说明点击的列是DataGridViewButtonColumn列
string path = dgv.Rows[e.RowIndex].Cells[].Value.ToString();
if (Directory.Exists(path))
{
//打开文件夹
System.Diagnostics.Process.Start(path);
}
else
{
//打开文件所在文件夹
DirectoryInfo fi = new DirectoryInfo(path);
System.Diagnostics.Process.Start(fi.Parent.FullName);
}
}
}

单元格点击事件

4.导出datagridview数据到excel中,我做的比较麻烦,而且我导出的是datagridview绑定的数据源datatable,如果要导出datagridview中显示的数据,要先把datagridview的数据存到datatable中,再导出。下面是导出方法

private void btn_export_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtPath.Text))
{
MessageBox.Show("保存路径不能为空!", "提示");
return;
}
Task tk = new Task(Way);
//MessageBox.Show("正在导出请稍后...");
lb1.Visible = true;
lb1.Text = "数据导出中,请稍后...";
txtPath.Visible = false;
btn_export.Enabled = false;
tk.Start();
} private void Way()
{
dataexcel.DataExcelExport(dt, txtPath.Text, "错误数据导出", "EXCEL");
MessageBox.Show("数据导出完成");
btn_export.Enabled = true;
txtPath.Visible = true;
lb1.Visible = false;
}

导出datagridview数据

调用的类的方法:

public class DataExcelExportHandle
{
public delegate void Del_error(string StrError);
public static event Del_error aa;
public void DataExcelExport(DataTable QueryTable, string FilePath, string TableName, string DbType)
{
List<string> ErrorList = new List<string>();
string Query = string.Empty;//数据导出语句
try
{
//判断Excel版本
string StrVerSion = FilePath.Split('.')[].ToString();
string DataConnect = string.Empty;
if (DbType == "EXCEL")
{
if (StrVerSion.ToLower() == "xls")
{
DataConnect = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + FilePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=2'";
}
if (StrVerSion.ToLower() == "xlsx")
{
//DataConnect = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + FilePath + ";Extended Properties='Excel 12.0 Macro; HDR = NO'";
DataConnect = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + FilePath + ";Extended Properties='Excel 12.0 Xml; HDR = NO'";
}
}
//else
//{
// if (StrVerSion.ToLower() == "mdb")
// {
// DataConnect = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source =" + FilePath;
// //判断ACCESS数据文件是否存在 不存在则创建
// if (!File.Exists(FilePath))
// {
// Catalog catalog = new Catalog();
// catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Jet OLEDB:Engine Type=5");
// }
// }
// if (StrVerSion.ToLower() == "accdb")
// {
// DataConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath;
// //判断ACCESS数据文件是否存在 不存在则创建
// if (!File.Exists(FilePath))
// {
// ADOX.Catalog catalog = new ADOX.Catalog();
// catalog.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";");
// }
// }
//} //string ConnectStr = CurrencyHandle.GetXmlNumber("DataBaseDeploy", "SqlConnect");
//DataTable dt = SqlDataBaseHandle.GetTable(StrDataQuery, ConnectStr);
//根据表名字段动态创建表字段
string CreateColumn = "create table " + TableName + " (";
string QueryNumberStr = "insert into " + TableName + " (";
for (int i = ; i < QueryTable.Columns.Count; i++)
{
CreateColumn = CreateColumn + QueryTable.Columns[i].ColumnName + " text,";
QueryNumberStr = QueryNumberStr + QueryTable.Columns[i].ColumnName + ",";
}
QueryNumberStr = QueryNumberStr.TrimEnd(',');
CreateColumn = CreateColumn.TrimEnd(',');
CreateColumn = CreateColumn + ")";
//创建表
OleDataBaseHandle.OleConnectOpen(DataConnect);
OleDataBaseHandle.OleImplement(CreateColumn);
Query = QueryNumberStr + ") values(";
for (int i = ; i < QueryTable.Columns.Count; i++)
{
Query = Query + "@" + QueryTable.Columns[i].ColumnName + ",";
}
Query = Query.Substring(, Query.Length - );
Query = Query + ")";
int CountIndex = ;//记录数据条数
string SysTable = TableName;
#region 数据导出
for (int i = ; i < QueryTable.Rows.Count; i++)
{
try
{
//当导出数据超过限制时将自动创建新的表
if (DbType == "EXCEL")
{
if (StrVerSion.ToLower() == "xlsx")
{
if (i > CountIndex * )
{
CreateColumn = CreateColumn.Replace(TableName, SysTable + CountIndex);
OleDataBaseHandle.OleImplement(CreateColumn);
Query = Query.Replace(TableName, SysTable + CountIndex);
TableName = TableName + CountIndex;
CountIndex++;
}
}
else
{
if (i > CountIndex * )
{
CreateColumn = CreateColumn.Replace(TableName, SysTable + CountIndex);
OleDataBaseHandle.OleImplement(CreateColumn);
Query = Query.Replace(TableName, SysTable + CountIndex);
TableName = TableName + CountIndex;
CountIndex++;
}
}
}
List<OleDbParameter> oleList = new List<OleDbParameter>();
for (int k = ; k < QueryTable.Columns.Count; k++)
{
OleDbParameter prop = null;
try
{
if (QueryTable.Rows[i][k] == null)
{
prop = new OleDbParameter("@" + QueryTable.Columns[k].ColumnName, "");
}
else
{
prop = new OleDbParameter("@" + QueryTable.Columns[k].ColumnName, QueryTable.Rows[i][k].ToString());
}
}
catch (Exception excc)
{
aa("导出失败" + Query);
ErrorList.Add(excc.Message);
}
oleList.Add(prop);
}
if (!OleDataBaseHandle.OleImplement(Query, oleList))
{
aa("导出失败" + Query);
ErrorList.Add("导出失败" + Query);
} }
catch (Exception exx)
{
aa(exx.Message + Query);
ErrorList.Add(exx.Message + Query);
}
}
#endregion
OleDataBaseHandle.OleConnectColse();
}
catch (Exception ex)
{
aa(ex.Message + Query);
ErrorList.Add(ex.Message + Query); }
finally
{
if (ErrorList != null && ErrorList.Count > )
{
ToolHelper.ErrorInfoSave(ErrorList);
}
}
}
}

上面方法调用的ole操作类:

https://www.cnblogs.com/Li232/p/10813918.html

/// <summary>
/// Ole操作类
/// </summary>
public class OleDataBaseHandle
{
private static OleDbConnection con = null;
private static OleDbCommand cmd = null;
/// <summary>
/// 通过文件路径 获取文件的所有表名
/// </summary>
/// <param name="Filename">文件路径</param>
/// <returns></returns>
public static DataTable GetFileTableName(string Filename)
{
string DbConnect = string.Empty;
try
{
DbConnect = GetConnect(Filename);//通过文件获取连接字符串
con = new OleDbConnection(DbConnect);
con.Open();
DataTable dt = new DataTable();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });
return dt;
}
catch (Exception)
{
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
if (con != null)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
} }
/// <summary>
/// 通过文件路径和表名获取所有数据(现支持EXCEL2003和ACCESS2003)
/// </summary>
/// <param name="Filename">文件路径</param>
/// <param name="TableName">表名</param>
/// <returns></returns>
public static DataTable GetFileTableData(string Filename, string TableName)
{
string DbConnect = string.Empty;
try
{
DbConnect = GetConnect(Filename);//通过文件获取连接字符串
con = new OleDbConnection(DbConnect);
con.Open();
DataTable dt = new DataTable();
cmd = new OleDbCommand("select * from [" + TableName + "]", con);
OleDbDataAdapter dapter = new OleDbDataAdapter(cmd);
dapter.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
if (con != null)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
} }
}
/// <summary>
/// 通过数据文件和表名获取该表的所有列(现支持EXCEL2003和ACCESS2003)
/// </summary>
/// <param name="Filename">文件路径</param>
/// <param name="TableName">文件表名</param>
/// <returns></returns>
public static DataTable GetFileTableName(string Filename, string TableName)
{
List<string> ErrorList = new List<string>();
OleDbCommand cmd = null;
OleDbConnection con = null;
string DbConnect = string.Empty;
try
{
DbConnect = GetConnect(Filename);//通过文件获取连接字符串
con = new OleDbConnection(DbConnect);
con.Open();
DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, TableName, null });
if (dt == null || dt.Rows.Count < )
{
return null;
}
else
{
return dt;
}
}
catch (Exception ex)
{
ErrorList.Add(ex.Message);
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
if (con != null)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
} }
}
/// <summary>
/// 通过语句执行返回结果true false
/// </summary>
/// <param name="StrQuery">执行的SQL语句</param>
/// <returns></returns>
public static bool OleImplement(string StrQuery, string ConnectStr)
{
try
{
con = new OleDbConnection(ConnectStr);
con.Open();
cmd = new OleDbCommand(StrQuery, con);
int a = cmd.ExecuteNonQuery();
if (a != )
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
if (con != null)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
}
/// <summary>
/// 通过数据文件和表名获取该表的所有列
/// </summary>
/// <param name="StrQuery">所执行的SQL语句</param>
/// <returns></returns>
public static bool OleImplement(string StrQuery)
{
try
{
cmd = new OleDbCommand(StrQuery, con);
int a = cmd.ExecuteNonQuery();
if (a != )
{
return true;
}
else
{
return false;
}
}
catch (Exception exxx)
{
return false;
}
}
/// <summary>
/// 通过连接字符串建立长链接
/// </summary>
/// <param name="StrConnect">连接数据库字符串</param>
public static void OleConnectOpen(string StrConnect)
{
con = new OleDbConnection(StrConnect);
con.Open();
}
/// <summary>
/// 关闭长链接并释放资源
/// </summary>
public static void OleConnectColse()
{
if (cmd != null)
{
cmd.Dispose();
}
if (con != null)
{
if (con.State == ConnectionState.Open)
{
con.Close();
con.Dispose();
}
}
}
/// <summary>
/// 执行参数化SQL语句
/// </summary>
/// <param name="StrQuery">所执行的SQL语句</param>
/// <param name="para">参数化集合</param>
/// <returns></returns>
public static bool OleImplement(string StrQuery, List<OleDbParameter> para)
{
try
{
cmd = new OleDbCommand(StrQuery, con);
foreach (var item in para)
{
cmd.Parameters.Add(item);
}
cmd.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 通过文件路径返回ADO连接字符串
/// </summary>
/// <param name="Filename">文件路径</param>
/// <returns></returns>
public static string GetConnect(string Filename)
{
string DbConnect = string.Empty;
if (Filename.Split('.')[].ToLower() == "xls")
{
DbConnect = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + Filename + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=2'";
}
else if (Filename.Split('.')[].ToLower() == "xlsx")
{
DbConnect = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + Filename + ";Extended Properties='Excel 12.0 Macro; HDR = NO'";
}
else if (Filename.Split('.')[].ToLower() == "mdb")
{
DbConnect = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source =" + Filename;
}
else if (Filename.Split('.')[].ToLower() == "accdb")
{
DbConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Filename;
}
else
{
DbConnect = null;
}
return DbConnect;
} /// <summary>
/// 执行参数化SQL语句
/// </summary>
/// <param name="StrQuery">所执行的SQL语句</param>
/// <returns></returns>
public static DataTable OleGetTable(string FilePath, string StrQuery)
{
OleDbConnection objConn = null;
DataTable dt = new DataTable();
try
{
string StrVerSion = FilePath.Split('.')[].ToString();
string DataConnect = string.Empty;
if (StrVerSion.ToLower() == "xls")
{
DataConnect = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + FilePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
}
if (StrVerSion.ToLower() == "xlsx")
{
DataConnect = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + FilePath + ";Extended Properties='Excel 12.0 Xml; HDR = NO'";
}
objConn = new OleDbConnection(DataConnect);
objConn.Open();//打开连接
//RegistryKey reg_TypeGuessRows = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Jet\4.0\Engines\Excel");
//reg_TypeGuessRows.SetValue("TypeGuessRows", 65000);
cmd = new OleDbCommand(StrQuery, objConn);
OleDbDataAdapter adr = new OleDbDataAdapter();
adr.SelectCommand = cmd;
adr.Fill(dt);
objConn.Close();
//OleDbDataReader reader = cmd.ExecuteReader();
//dt.Load(reader); //直接把reader转换为datatable
return dt;
}
catch(Exception ex)
{
ToolHelper.ErrorInfoSave(ex.Message);
return null;
}
} }

上述方法中用到的ole操作类

推荐两个百度到的导出datagridview数据的博客地址,这两个写的很简单:

https://www.cnblogs.com/chaowang/p/6265698.html

https://www.cnblogs.com/kongxiaoshuang/p/6062368.html 

 

winform datagridview控件使用的更多相关文章

  1. C#实现WinForm DataGridView控件支持叠加数据绑定

    我们都知道WinForm DataGridView控件支持数据绑定,使用方法很简单,只需将DataSource属性指定到相应的数据源即可,但需注意数据源必须支持IListSource类型,这里说的是支 ...

  2. winform DataGridView控件开发经验

    1.不让DataGridView控件自动生成列 设置AutoGenerateColumns 为false. dgTicket.AutoGenerateColumns = false; //将自动生成列 ...

  3. Winform DataGridView控件添加行号

      有很多种方法,这里介绍三种: A: 控件的RowStateChanged事件中添加,RowStateChanged事件是在行的状态更改(例如,失去或获得输入焦点)时发生的事件: e.Row.Hea ...

  4. 实现winform DataGridView控件判断滚动条是否滚动到当前已加载的数据行底部

    判断 DataGridView控件滚动条是否滚动到当前已加载的数据行底部,其实方法很简单,就是为DataGridView控件添加Scroll事件,然后写入以下代码就可以了,应用范围:可实现分部加载数据 ...

  5. winform DataGridView控件判断滚动条是否滚动到当前已加载的数据行底部 z

    http://www.zuowenjun.cn/post/2015/05/20/162.html 判断 DataGridView控件滚动条是否滚动到当前已加载的数据行底部,其实方法很简单,就是为Dat ...

  6. WinForm DataGridView控件、duck布局

    1.DataGridView控件 显示数据表 (1)后台数据绑定: List<xxx> list = new List<xxx>(); dataGridView1.DataSo ...

  7. Winform DataGridView控件在业务逻辑上的简单使用

    需要对文字列表进行处理,然后用到DataGridView控件来处理,记录一下.效果如下: 主要是想通过禁用和取消单元格选择来使图标单元格呈现出鼠标点击的效果.因为有个单元格选择的问题困扰着我. 是这样 ...

  8. Winform(DataGridView)控件及通过此控件中实现增删改查

    DataGridView:显示数据表,通过此控件中可以实现连接数据库,实现数据的增删改查 一.后台数据绑定:    List<xxx> list = new List<xxx> ...

  9. 如何在winform DataGridView控件的DataGridViewButtonColumn按钮列中禁用按钮

    原文:http://msdn.microsoft.com/en-us/library/ms171619(v=vs.85).ASPX public class DataGridViewDisableBu ...

随机推荐

  1. 使用Deployment控制器创建Pods并使Service发布到外网可访问

    由于NFS支持节点共同读取及写入,所以可使用Deployment控制器创建多个Pod,并且每一个Pod都共享同一个目录 k8s-master kubnet@hadoop2 volumes]$ vim ...

  2. 二、urllib库的使用详解

    一.urllib2库的基本使用 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地. 在Python中有很多库可以用来抓取网页,我们先学习urllib2. urllib2 是 ...

  3. python 和 R 语言 中的 range() 函数

    1.python 中的 range() 函数生成整数序列,常用于 for 循环的迭代. 示例: 2.R 语言中的 range() 函数返回一个数值向量中的最小值和最大中,常用于求极差. 示例: 按语: ...

  4. python字符串使用方法归纳

    字符串的意思就是“一串字符”,比如“Hello,Charlie”是一个字符串,“How are you?”也是一个字符串. Python 要求字符串必须使用引号括起来,使用单引号也行,使用双引号也行, ...

  5. Comet OJ 夏季欢乐赛 Gree的心房

    Comet OJ 夏季欢乐赛 Gree的心房 题目传送门 题目描述 据说每一个走进Gree哥哥心房的小姑娘都没有能够再走出来-- 我们将Gree哥哥的心房抽象成一个n \times mn×m的地图,初 ...

  6. android开发环境sdk manager无法更新问题

    由于无法fq,也没有vpn,建议各位新手不用sdk manager去安装,直接下载bundle包,就不用去折腾各种开发环境了.推荐bundle下载地址:http://adt.android-studi ...

  7. ZBX_TCP_READ() time out windows

    zabbix 客户端无法推送数据,日志显示在启动的时候ZBX_TCP_READ() time out windows, 场景:agent 到proxy的10051通,proxy到agnet的10050 ...

  8. Java class 和public class 区别

    1.类的访问权限 为了控制某个类的访问权限,修饰词必须出现在关键字class之前.例如:public class Student {}    在编写类的时候可以使用两种方式定义类:    (A)pub ...

  9. 转载:tensorflow保存训练后的模型

    训练完一个模型后,为了以后重复使用,通常我们需要对模型的结果进行保存.如果用Tensorflow去实现神经网络,所要保存的就是神经网络中的各项权重值.建议可以使用Saver类保存和加载模型的结果. 1 ...

  10. 2014(5)系统设计,web应用

    [案例五](共25分) 阅读以下关于Web应用的叙述,在答题纸上回答问题1至问题2. [说明] 某软件公司拟为其客户开发一套基于Web的电子商务系统,该系统向终端用户提供在线购物功能.近期,项目组召开 ...