datagridview 绑定,datagridview数据绑定

将乐信息网 http://www.jianglexinxi.cn 2020-09-17 08:07 出处:网络
datagridview 绑定,datagridview数据绑定,C# winform DataGridView 绑定数据的的几种方法 String strConn = \"Data Source=.;Initial Catalog=His;User ID=sa;Password=*****\";

datagridview 绑定,datagridview数据绑定,C# winform 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", conn);
 reader = command.ExecuteReader();
 return ConvertToDataTable(reader);
}

 

 

public DataTable ConvertToDataTable(SqlDataReader dataReader)//SqlDataReader转换为DataTable
 DataTable dt = new DataTable();
 DataTable schemaTable = dataReader.GetSchemaTable();
 //动态构建表,添加列
 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);
 }

 



datagridview 绑定的相关网页热门搜索词

datagridview数据绑定|datagridview解除绑定|datagridview添加数据|datagridview复选框|datagridview修改数据|datagridview分页显示|datagridview行高|datagridview表单|datagridview可编辑|

本文标题:datagridview 绑定,datagridview数据绑定
http://www.jianglexinxi.cn/yanergaozhi/481700.html

0

精彩评论

暂无评论...
验证码 换一张
取 消