如何在DataGridView中的每列添加CellContentClick事件 [英] How to add a CellContentClick Event per Column in a DataGridView

查看:306
本文介绍了如何在DataGridView中的每列添加CellContentClick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以按列设置CellContentClick事件方法,例如

Is it possible to set a CellContentClick Event method per Column, e.g. as a method of a DataGridViewColumn.

如果仅针对此列而不是像整个DataGridView.CellContentClick一样发生整个DataGridView的事件发生,则此方法将运行。

This method would run if a CellContentClick happens for only this column instead of the whole DataGridView like the normal DataGridView.CellContentClick does.

我需要这个来派生DataGridViewButtonColumn。因此,如有必要,可以在此DataGridViewColumn中添加我自己的方法/属性。

I need this for a derivation of a DataGridViewButtonColumn. So it would be possible to add my own methods/properties to this DataGridViewColumn if this is neccessary.

推荐答案

您可以定义一个事件为自定义列类型,然后覆盖自定义单元格的 OnContentClick 并引发该列的事件。

You can define an event for the custom column type, then override OnContentClick of the custom cell and raise the event of the column.

仅请记住,要使用它,您需要通过代码预订事件,因为该事件属于 Column ,并且您无法在设计器中看到它。

Just keep in mind, to use it, you need to subscribe the event through the code because the event belongs to Column and you cannot see it in designer.

示例

在这里,我创建了一个自定义按钮列,您可以订阅该按钮列c $ c> ContentClick 事件。这样,您无需检查 DataGridView CellContentClick 事件是否由于单击而引发

Here I've created a custom button column which you can subscribe to for its ContentClick event. This way you don't need to check if the CellContentClick event of the DataGridView is raised because of a click on this button column.

using System.Windows.Forms;
public class MyDataGridViewButtonColumn : DataGridViewButtonColumn
{
    public event EventHandler<DataGridViewCellEventArgs> ContentClick;
    public void RaiseContentClick(DataGridViewCellEventArgs e)
    {
        ContentClick?.Invoke(DataGridView, e);
    }
    public MyDataGridViewButtonColumn()
    {
        CellTemplate = new MyDataGridViewButtonCell();
    }
}
public class MyDataGridViewButtonCell : DataGridViewButtonCell
{
    protected override void OnContentClick(DataGridViewCellEventArgs e)
    {
        var column = this.OwningColumn as MyDataGridViewButtonColumn;
        column?.RaiseContentClick(e);
        base.OnContentClick(e);
    }
}

要使用它,您需要通过以下方式订阅活动代码,因为该事件属于 Column 并且您无法在设计器中看到它:

To use it, you need to subscribe the event through the code because the event belongs to Column and you cannot see it in the designer:

var c1 = new MyDataGridViewButtonColumn() { HeaderText = "X" };
c1.ContentClick += (obj, args) => MessageBox.Show("X Cell Clicked");

这篇关于如何在DataGridView中的每列添加CellContentClick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆