實現效果:

知識運用:
ListView控件中的Items集合的Clear方法 //從listView控件的數據項集合中移除所有數據項
補充:可以使用Remove或RemoveAt方法從集合中移除單個數據項
實現代碼:
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, "錯誤");
}
}
