在Datagridview控件显示Datatable数据

定义链接字符串,建立一个新的链接实例;

private static string connString = @"Data Source=DESKTOP-GVLLFG5\SQLEXPRESS;Initial Catalog=db_Mytime;Integrated Security=True";
        public static SqlConnection connection = new SqlConnection(connString);//初始化sqlConnnection的新实例

根据输入的表名获得一个数据表;

 public DataTable GetDataTable(string TableName)
        { 
            try
            {
                string sql = "select * from " + TableName ;
                sqlda = new SqlDataAdapter(sql,connection);
                new SqlCommandBuilder(sqlda);
                DataTable dt = new DataTable();
                sqlda.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "软件提示");
                throw ex;
            }
        }

将DataTable数据表逐个单元格显示在datagridview上

private void Form1_Load(object sender, EventArgs e)
        {

            dataGridView2.Columns.Add("RowState", "rowstate");//添加新列
            DataTable dt = oper.GetDataTable("db_time");//获取数据表
            foreach (DataColumn col in dt.Columns)
            {
                dataGridView2.Columns.Add(col.ColumnName, col.ColumnName);
            }
            dataGridView2.Rows.Clear();
            dataGridView2.Rows.Add(dt.Rows.Count);//增加同等数量的行数
            int i = 0;
            foreach (DataRow row in dt.Rows)//逐个读取单元格的内容;
            {
                DataGridViewRow r1 = dataGridView2.Rows[i];
                r1.Cells[0].Value = row.RowState.ToString();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    r1.Cells[j + 1].Value = row[j].ToString();
                }
                i++;
            }

        } 

你可能感兴趣的:(在Datagridview控件显示Datatable数据)