第一学期 C#容易忘记的方法
2021-07-20 05:13
第一学期 C#容易忘记的方法
-
如何将数据加载到ListView中
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();
}