将数据库数据添加到ListView控件中

实现效果:

  

知识运用:

  ListView控件中的Items集合的Clear方法  //从listView控件的数据项集合中移除所有数据项

  补充:可以使用RemoveRemoveAt方法从集合中移除单个数据项

实现代码:

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string P_Connection = string.Format(        //创建数据库连接字符串
                @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|" +
                @"\Database1.mdf;Integrated Security=True;User Instance=True");
                SqlConnection P_sqlConnection =             //创建连接对象
                    new SqlConnection(P_Connection);
                P_sqlConnection.Open();                      //连接到数据库
                SqlCommand P_sqlCommand = new SqlCommand(       //创建命令对象
                    "select * from fruit", P_sqlConnection);
                SqlDataReader P_Read = P_sqlCommand.ExecuteReader();        //得到数据读取器
                while (P_Read.Read())                                           //读取数据
                {
                    ListViewItem lv = new ListViewItem(P_Read[0].ToString());

                    lv.SubItems.Add(P_Read[1].ToString());
                    lv.SubItems.Add(P_Read[2].ToString());
                    listView1.Items.Add(lv);
                }
                P_sqlConnection.Close();        //关闭数据库连接
            }
            catch (Exception ex)
            {
                MessageBox.Show(        //弹出消息对话框
                    "数据读取失败\n" + ex.Message, "错误");
            }
        }

猜你喜欢

转载自www.cnblogs.com/feiyucha/p/10162528.html