第一学期 C#容易忘记的要领

时间:2021-12-30 07:02:52

第一学期  C#容易忘记的要领 2017-12-16如何将数据加载到ListView中

要领1:

 private void LoadListView()
  {
    string sql = "select * from employee";
    lvEmp.Items.Clear();
    SqlDataReader dr = DBHelper.ExecuteReader(sql);
    while (dr.Read())
    {
    ListViewItem lvi = new ListViewItem(dr["Id"].ToString());
    lvi.SubItems.AddRange(
    new string[] {
    dr[" "].ToString(),
    dr[" "].ToString(),
    dr[" "].ToString(),
    dr[" "].ToString(),
    });
    lvEmp.Items.Add(lvi);
  }
    dr.Close();
    DBHelper.Closecon();

  }

要领二:

创建DBhelper类,结构要领

public static DataTable GetTable(string sql)
   {
      DataTable dt = new DataTable();
      SqlDataAdapter sda = new SqlDataAdapter(sql, GetConnection());
      sda.Fill(dt);
      return dt;
   }

 private void LoadListView()

  {

     string sql = "select * from employee";

     lvEmp.Items.Clear();

     DataTable dt = DBHelper.GetTable(sql);

     foreach (DataRow dr in dt.Rows)//遍历数据表中的每一行

      {

        ListViewItem lvi = new ListViewItem(dr[0].ToString());

        lvi.SubItems.AddRange(

        new string[] {

        dr[1].ToString(),

        dr[2].ToString(),

        dr[3].ToString(),

        dr[4].ToString()

      });

    lvEmp.Items.Add(lvi);

   }

    DBHelper.Closecon();