您好,欢迎来到意榕旅游网。
搜索
您的当前位置:首页C#winformDataGridView绑定数据的的几种方法

C#winformDataGridView绑定数据的的几种方法

来源:意榕旅游网
C#winformDataGridView绑定数据的的⼏种⽅法

1.⽤DataSet和DataTable为DataGridView提供数据源

String strConn = \"Data Source=.;Initial Catalog=His;User ID=sa;Password=*****\";SqlConnection conn = new SqlConnection(strConn);String sql= \"select * from EMPLOYEE \"; conn.Open();

SqlCommand cmd = new SqlCommand(sqlId, conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet();da.Fill(ds, \"EMPLOYEE\"); dataGridView1.DataSource = ds;

this.dataGridView1.AutoGenerateColumns = false;//是否⾃动⽣成列dataGridView1.DataMember = \"EMPLOYEE\"; conn.Close();

2.创建DataGridViewRow 对象Add添加⾏

String sql_conn= \"Data Source=.;Initial Catalog=His;User ID=sa;Password=*****\";System.Data.DataTable table =return_table(sql_conn);foreach (System.Data.DataRow date in table.Rows){

DataGridViewRow newRow = new DataGridViewRow(); newRow.CreateCells(this.dataGridView1); newRow.Cells[0].Value = date[0].ToString(); newRow.Cells[1].Value = date[1].ToString(); newRow.Cells[2].Value = date[2].ToString(); newRow.Cells[3].Value = date[3].ToString(); newRow.Cells[4].Value = date[4].ToString(); dataGridView1.Rows.Add(newRow); }

public System.Data.DataTable return_table(string sql_conn){

SqlConnection conn = new SqlConnection(sql_conn); SqlDataReader reader = null; conn.Open();

SqlCommand command = new SqlCommand(\"select

RegID,Name,Area,RoomNO,BedNO from EMPLOYEE\ reader = command.ExecuteReader(); return ConvertToDataTable(reader);}

public DataTable ConvertToDataTable(SqlDataReader dataReader)//SqlDataReader转换为DataTable {

DataTable dt = new DataTable();

DataTable schemaTable = dataReader.GetSchemaTable(); try {

//动态构建表,添加列

foreach (DataRow dr in schemaTable.Rows) {

DataColumn dc = new DataColumn(); //设置列的数据类型

dc.DataType = dr[0].GetType(); //设置列的名称

dc.ColumnName = dr[0].ToString(); //将该列添加进构造的表中 dt.Columns.Add(dc); }

//读取数据添加进表中 while (dataReader.Read()) {

DataRow row = dt.NewRow(); //填充⼀⾏数据

for (int i = 0; i < schemaTable.Rows.Count; i++) {

row[i] = dataReader[i].ToString(); }

dt.Rows.Add(row);

row = null; }

dataReader.Close(); schemaTable = null; return dt; }

catch (Exception ex) {

//抛出异常

throw new Exception(ex.Message); } }

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- yrrf.cn 版权所有 赣ICP备2024042794号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务