1 DataSet ds = new DataSet(); 2 SqlDataAdapter apt; 3 #region 窗体加载事件 4 private void Form1_Load(object sender, EventArgs e) 5 { 6 string sql = "SELECT * FROM dbo.BookInfo"; 7 apt = new SqlDataAdapter(sql,SQLHelper.con); 8 apt.Fill(ds, "BookInfo");//把BookInfo表数据填充到dataset里面 9 this.lvView.BorderStyle = BorderStyle.FixedSingle;//listview边框样式 10 this.lvView.GridLines = true;//显示网格 11 this.lvView.FullRowSelect = true;//当被选中时,一行变颜色,选中一行 12 for (int i = 0; i < ds.Tables["BookInfo"].Columns.Count; i++)//遍历BookInfo表中的列 13 { 14 ColumnHeader ch = new ColumnHeader();//创建标题头对象 15 ch.Width = 60;//标题头宽度60 16 ch.TextAlign = HorizontalAlignment.Center;//文本居中对齐 17 ch.Text = ds.Tables["BookInfo"].Columns[i].ColumnName;//标题头显示列的名称 18 this.lvView.Columns.Add(ch);//将标题头添加到listview中 19 } 20 for (int i = 0; i < ds.Tables["BookInfo"].Rows.Count; i++)//遍历BookInfo中所有行 21 { 22 ListViewItem lvi = new ListViewItem(); 23 lvi.SubItems[0].Text = ds.Tables["BookInfo"].Rows[i]["bookId"].ToString(); 24 lvi.SubItems.AddRange(new string []{ 25 ds.Tables["BookInfo"].Rows[i]["bookName"].ToString(), 26 ds.Tables["BookInfo"].Rows[i]["bookAuthor"].ToString(), 27 ds.Tables["BookInfo"].Rows[i]["bookAuthor"].ToString(), 28 ds.Tables["BookInfo"].Rows[i]["bookPrice"].ToString(), 29 ds.Tables["BookInfo"].Rows[i]["publish"].ToString() }); 30 this.lvView.Items.Add(lvi);//将数据添加到listview中 31 } 32 } 33 #endregion