【问题标题】:Visual C# - Associate event handler with CellDoubleClick eventVisual C# - 将事件处理程序与 CellDoubleClick 事件关联
【发布时间】:2010-11-23 02:33:48
【问题描述】:

我在 Visual Studio 中工作,并尝试在用户双击 DataGridView 单元格时从它获取信息。我基本上像任何其他 Click 事件一样设置了 CellDoubleClick 事件,但这似乎不起作用。

代码:

Form1.cs

private void dataGridView1_CellDoubleClick(Object sender, DataGridViewCellEventArgs e)
    {

        System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
        messageBoxCS.AppendFormat("{0} = {1}", "ColumnIndex", e.ColumnIndex);
        messageBoxCS.AppendLine();
        messageBoxCS.AppendFormat("{0} = {1}", "RowIndex", e.RowIndex);
        messageBoxCS.AppendLine();
        MessageBox.Show(messageBoxCS.ToString(), "CellDoubleClick Event");
    }

Form1.Designer.cs中的相关代码

this.dataGridView1.CellDoubleClick += new System.EventHandler(this.dataGridView1_CellDoubleClick);

我在 Form1.Designer 代码中收到一条错误消息:“'dataGridView1_CellDoubleClick' 没有重载与委托 'System.EventHandler' 匹配。

我怎样才能让双击正常工作? 谢谢。

【问题讨论】:

    标签: c# datagridview overloading


    【解决方案1】:

    CellDoubleClick 事件是 DataGridViewCellEventHandler,而不是 EventHandler`。

    您应该使用设计器添加事件句柄,这将自动使用正确的委托类型。
    您不应手动编辑设计器生成的代码。

    通常,在添加事件处理程序时,您不应显式创建委托。
    相反,你可以写

    myGrid.CellDoubleClick += MyGrid_CellDoubleClick;
    

    【讨论】:

    • 好吧,我对 Visual Studio 不是很擅长,而且我有点不知所措,试图让双击工作。阅读您的评论后,我仔细查看了设计师并找到了事件按钮。现在它起作用了。谢谢。
    • 如果你有时间,请像我 5 岁一样向我解释为什么不能简单地做 += new EventHandler(MyGrid_CellDoubleClick);处理这个事件,我不明白。 :)
    • @JazzCat:因为该事件被声明为不同的类型。 msdn.microsoft.com/en-us/library/ms173171
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多