1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Drawing;
5 using System.Linq;
6 using System.Text;
7 using System.Threading.Tasks;
8 using System.Windows.Forms;
9
10 using System.Data;
11 using System.Data.SqlClient;
12
13 namespace DataBase_SqlDataAdapter
14 {
15 public partial class Form1 : Form
16 {
17 public Form1()
18 {
19 InitializeComponent();
20 }
21
22 private void button1_Click(object sender, EventArgs e)
23 {
24 // 清理listBox1
25 listBox1.Items.Clear();
26
27 //从数据库Employee中读取教师名字存储到listBox1
28 BindDataWithListbox();
29 }
30
31 //从数据库Employee中读取教师名字存储到listBox1
32 private void BindDataWithListbox()
33 {
34 // 连接数据库的字符串
35 string selectConnectionString = "Server = 192.0.0.1; DataBase = DuanLaoYeDataBase; UID = DuanLaoYe; PWD = 123456";
36 // 执行查询Employee表的T-SQL语句
37 string selectCommandText = "select * from Employee";
38 //创建适配器 : 适配器会自动打开和关闭适配器自己打开的数据库连接
39 using( SqlDataAdapter sda= new SqlDataAdapter(selectCommandText, selectConnectionString) )
40 {
41 // 在内存中创建数据表
42 DataTable dt = new DataTable();
43
44 // 将适配器读取到的结果集存储到DataTable中
45 sda.Fill(dt);
46
47 // 方法1 : 绑定数据源: 从DataTable表中获取
48 listBox1.DataSource = dt;
49 listBox1.DisplayMember = "Emp_Name"; // Employee表的Emp_Name字段名
50 listBox1.ValueMember = "Emp_ID"; // Employee表的Emp_ID字段名
51
52 /***********************************************************************
53 * 方法2:
54 listBox1.BeginUpdate();
55 foreach(DataRow dr in dt.Rows)
56 {
57 listBox1.Items.Add(dr[1].ToString().Trim());
58 }
59 listBox1.EndUpdate();
60 ***********************************************************************/
61
62 }
63 }
64 }
65 }