我正在尝试使我的ListView能够单击或双击,但是我的listview1_1点击似乎不起作用。每当我单击所选项目时,都没有消息框弹出。我按照创建单击事件的通常格式进行操作,但似乎没有效果。是因为我将数据从数据库加载到ListView中,而不是在ListView内部创建数据所致吗?非常感谢!
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace sundayschoolproject
{
public partial class Form1 : Form
{
string con = ("Data Source=ZTABASSUM\\SQLEXPRESS01;Initial Catalog= Sunday School;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listView1.GridLines = true;
listView1.View = View.Details;
//Add Columns
listView1.Columns.Add("ParentName", 100);
listView1.Columns.Add("Address", 150);
listView1.Columns.Add("City", 100);
listView1.Columns.Add("State", 50);
listView1.Columns.Add("Zipcode", 100);
listView1.Columns.Add("Phone", 150);
}
private void button1_Click(object sender, EventArgs e)
{
string sql = ("Select * from Family");
SqlConnection connection = new SqlConnection(con);
SqlCommand cmd = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = cmd.ExecuteReader();
listView1.Items.Clear();
while (dr.Read())
{
ListViewItem lv = new ListViewItem(dr.GetString(0));
lv.SubItems.Add(dr.GetString(1));
lv.SubItems.Add(dr.GetString(2));
lv.SubItems.Add(dr.GetString(3));
lv.SubItems.Add(dr.GetString(4));
lv.SubItems.Add(dr.GetString(5));
listView1.Items.Add(lv);
}
dr.Close();
connection.Close();
}
private void listView1_Click(object sender, MouseEventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
MessageBox.Show("You clicked " + listView1.SelectedItems[0].Text);
}
else
{
MessageBox.Show("Please select an item");
}
}
}
}