拉控键,创建一个简单的实例,如下图所示

将DataGridView里面的数据导入到Excel中

(1)将数据库数据导入DataGridView中

代码如下所示

 1         private DataTable _dtInfo = null;
 2         private DataView _dvInfo = null;
 3         //private DataGridView dgvInfo = null;
 4         public Demo()
 5         {
 6             InitializeComponent();
 7         }
 8         private void Form1_Load(object sender, EventArgs e)
 9         {
10             _dtInfo = GetData();
11             _dvInfo = new DataView(_dtInfo, "", "", DataViewRowState.CurrentRows);
12             dataGridView1.DataSource = _dvInfo;
13         }
14         private void button1_Click(object sender, EventArgs e)
15         {
16             InitData();
17         }
18 
19         private void InitData()
20         {
21             try
22             {
23                 if (_dtInfo != null)
24                 {
25                     _dtInfo.Rows.Clear();
26                 }
27                 string con, sql;
28                 con = @"Data Source=。 ;Initial Catalog=FirstDemo;User ID=sa;Pwd=123456";
29                 sql = "select * from Student";
30                 SqlConnection mycon = new SqlConnection(con);
31                 mycon.Open();
32                 SqlDataAdapter myda = new SqlDataAdapter(sql, con);
33                 DataSet myds = new DataSet();
34                 myda.Fill(_dtInfo);
35                 ////myda.Fill(myds, "test1");
36                 _dvInfo = new DataView(_dtInfo, "", "", DataViewRowState.CurrentRows);
37 
38                 dataGridView1.DataSource = _dvInfo;// myds.Tables["test1"];
39                 dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//选定一行
40                 dataGridView1.ReadOnly = true;//不可编辑
41                 dataGridView1.AllowUserToAddRows = false;//最后一行不显示
42                 dataGridView1.RowHeadersVisible = false;//第一列空白的不显示
43                 mycon.Close();
44             }
45             catch (Exception ex)
46             {
47                 MessageBox.Show("错误信息:" + ex.Message, "出现错误");
48             }
49         }
50 
51        
52         private DataTable GetData()
53         {
54             DataTable dtInfo = new DataTable();
55 
56             return dtInfo;
57         }
将数据库数据显示在DataGridView上

相关文章:

  • 2021-11-26
  • 2021-12-31
  • 2021-09-10
  • 2022-12-23
  • 2022-01-07
  • 2022-12-23
猜你喜欢
  • 2021-05-31
  • 2021-07-21
  • 2021-06-09
  • 2022-01-22
  • 2021-10-17
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案