【问题标题】:Double click on listbox item – C#双击列表框项目 - C#
【发布时间】:2021-12-17 20:44:52
【问题描述】:

我的列表框中有一些项目,当我双击其中一项时,我希望 MessageBox 显示我双击的项目的信息。例如,我单击一个项目“Item 1”,MessageBox 显示为“Item 1”文本。这是我现在的解决方案,但它返回项目的索引,而不是实际项目:

private void empLbx_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int index = this.empLbx.IndexFromPoint(e.Location);
            if (index != System.Windows.Forms.ListBox.NoMatches) 
            {
                MessageBox.Show(index.ToString());
            }
        }

【问题讨论】:

    标签: c# .net winforms listbox double-click


    【解决方案1】:

    试试这个:

    private void empLbx_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        int index = this.empLbx.IndexFromPoint(e.Location);
        if (index != System.Windows.Forms.ListBox.NoMatches) 
        {
           MessageBox.Show(empLbx.SelectedItem.ToString());
        }
    }
    

    【讨论】:

    • 谢谢,现在可以正常使用了!
    【解决方案2】:

    this 是你的表单而不是ListBox,你的列表框是变量sender。所以改变你的代码:

    int index = ((ListBox)sender).SelectedIndex;
    if(index != -1) 
        MessageBox.Show(index.ToString());
    

    如果未选择任何项目,或者列表框为空,则索引将为-1,因此if(index != -1) 处理两者。

    【讨论】:

      猜你喜欢
      • 2011-05-26
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多