最近做项目时,显示查询结果总需要绑定到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>0) { //dataGridView2.DataSource = dt; for (int i = 0; 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; }