图例

image.png
image.pngimage.png

  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. namespace DataBind_ListView
  12. {
  13. public partial class Form1 : Form
  14. {
  15. public Form1()
  16. {
  17. InitializeComponent();
  18. }
  19. private void btnBindData_Click(object sender, EventArgs e)
  20. {
  21. // 连接数据库
  22. SqlConnection myCon = new SqlConnection();
  23. myCon.ConnectionString = "Data Source=DESKTOP-VFJD28I;" +
  24. "Initial Catalog=db_Class;" +
  25. "Integrated Security=True"; // 这个数据库连接字符串在左侧服务器资源管理器-数据连接下-右击属性找到复制粘贴到这里
  26. myCon.Open();
  27. // 使用 SqlCommand 提交查询命令
  28. SqlCommand selectCMD = new SqlCommand("SELECT top 10 SNo,SName FROM tb_Student", myCon);
  29. // 创建SqlDataReader
  30. SqlDataReader dr = selectCMD.ExecuteReader();
  31. listView1.View = View.Details; // 设置显示模式
  32. listView1.FullRowSelect = true;
  33. // 将 DataReader 中的数据绑定到 ListView1
  34. while (dr.Read())
  35. {
  36. ListViewItem lv = new ListViewItem(dr[0].ToString());
  37. lv.SubItems.Add(dr[1].ToString());
  38. listView1.Items.Add(lv);
  39. }
  40. dr.Close();
  41. // 断开连接
  42. myCon.Close();
  43. }
  44. private void btnClearData_Click(object sender, EventArgs e)
  45. {
  46. listView1.Items.Clear();
  47. }
  48. }
  49. }