首页 > 技术文章 > C# winform DataGridView 绑定数据的的几种方法

zhuzhi0819 2019-09-25 15:54 原文

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", conn);
      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);
            }

        }

 



推荐阅读