简体   繁体   English

C# - ListView:如何处理 listViewItem 上的鼠标单击事件?

[英]C# - ListView : How to handle the mouse click event on a listViewItem?

Let's say I have a ListView on a form and it is populated with records.假设我在一个表单上有一个 ListView 并且它填充了记录。 How can I do this : when I click (single click) on a row , something has to happen - for example MessageBox.Show("row selected");我该怎么做:当我单击(单击)一行时,必须发生某些事情 - 例如 MessageBox.Show("row selected");

How to make this happen?如何做到这一点? Do I need a mouse click event ?我需要鼠标点击事件吗? And how can I do this?我该怎么做?

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var selectedItemText = (listBox1.SelectedItem ?? "(none)").ToString();
    MessageBox.Show("Selected: " + selectedItemText);
}

private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
    for (int i = 0; i < listBox1.Items.Count; i++)
    {
        var rectangle = listBox1.GetItemRectangle(i);
        if (rectangle.Contains(e.Location))
        {
            MessageBox.Show("Item " + i);
            return;
        }
    }

    MessageBox.Show("None");
}

@Tommy answer is for ListBox, this one is for ListView : @Tommy 的回答是针对 ListBox 的,这个是针对 ListView 的:

    private void listView1_MouseClick(object sender, MouseEventArgs e)
    {
        for (int i = 0; i < listView1.Items.Count; i++)
        {
            var rectangle = listView1.GetItemRect(i);
            if (rectangle.Contains(e.Location))
            {
                //Write your code here
                return;
            }
        }
    }

To prevent unwished behavior on ListView with checkboxes my solution is:为了防止使用复选框在 ListView 上出现不希望的行为,我的解决方案是:

private void lvMembers_MouseClick(object sender, MouseEventArgs e)
{
    for (int itemIndex = 0; itemIndex < lvMembers.Items.Count; itemIndex++)
    {
        ListViewItem item = lvMembers.Items[itemIndex];
        Rectangle itemRect = item.GetBounds(ItemBoundsPortion.Label);
        if (itemRect.Contains(e.Location))
        {
            item.Checked = !item.Checked;
            break;
        }
    }
}

If you want to select listview item on mouse click over it try this.如果你想在鼠标点击时选择列表视图项目,试试这个。

 private void timeTable_listView_MouseUp(object sender, MouseEventArgs e)
        {
            Point mousePos = timeTable_listView.PointToClient(Control.MousePosition);
            ListViewHitTestInfo hitTest = timeTable_listView.HitTest(mousePos);



            try
            {
            int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
            edit_textBox.Text = timeTable_listView.SelectedItems[0].SubItems[columnIndex].Text;
            }
            catch(Exception)
            {

            }



        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM