1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Data.SqlClient; 11 12 namespace 餐厅 13 { 14 public partial class Form1 : Form 15 { 16 17 18 19 public Form1() 20 { 21 InitializeComponent(); 22 } 23 24 private void Form1_Load(object sender, EventArgs e) 25 { 26 LoadDeskInfoByDelFlag(0); 27 28 } 29 30 private void LoadDeskInfoByDelFlag(int p) 31 { 32 //新建集合 33 List<DeskInfo> list = new List<DeskInfo>(); 34 //数据库字符串 35 string str = "Data Source=.;Initial Catalog=mysql;Integrated Security=True"; 36 //sql语句,flag为0的餐桌 37 string sql = "select DeskId,DeskName,DeskNamePinYin,DeskNum from DeskInfo where DeskDelFlag = " + p; 38 //string sql = "select * from DeskInfo"; 39 SqlConnection con = new SqlConnection(str); 40 con.Open(); 41 SqlCommand cmd = new SqlCommand(sql, con); 42 //cmd.reader为查询 43 SqlDataReader reader = cmd.ExecuteReader(); 44 //判断是否读取了一行 45 if (reader.HasRows) 46 { 47 //当读取的时候 48 while (reader.Read()) 49 { 50 //实例化餐桌类,为每个属性赋值,值为数据库里的值,进行类型转换 51 DeskInfo dk = new DeskInfo(); 52 dk.DeskId = Convert.ToInt32(reader["DeskId"]); 53 dk.DeskName = reader["DeskName"].ToString(); 54 dk.DeskNamePinYin = reader["DeskNamePinYin"].ToString(); 55 dk.DeskNum = reader["DeskNum"].ToString(); 56 //把属性添加进list 57 list.Add(dk); 58 } 59 60 } 61 //禁止自动生成列,没有delflag那一列了。 62 dgv.AutoGenerateColumns = false; 63 //绑定数据 64 dgv.DataSource = list; 65 66 //关闭数据库各项 67 con.Dispose(); 68 cmd.Dispose(); 69 reader.Dispose(); 70 } 71 } 72 }