简体   繁体   English

如何在 DataGridView 中为每列添加一个 CellContentClick 事件

[英]How to add a CellContentClick Event per Column in a DataGridView

Is it possible to set a CellContentClick Event method per Column, eg as a method of a DataGridViewColumn.是否可以为每列设置一个 CellContentClick 事件方法,例如作为 DataGridViewColumn 的方法。

This method would run if a CellContentClick happens for only this column instead of the whole DataGridView like the normal DataGridView.CellContentClick does.如果 CellContentClick 仅针对此列而不是像普通 DataGridView.CellContentClick 那样针对整个 DataGridView 发生,则此方法将运行。

I need this for a derivation of a DataGridViewButtonColumn.我需要这个来推导 DataGridViewButtonColumn。 So it would be possible to add my own methods/properties to this DataGridViewColumn if this is neccessary.因此,如果有必要,可以将我自己的方法/属性添加到此 DataGridViewColumn 中。

You can define an event for the custom column type, then override OnContentClick of the custom cell and raise the event of the column.您可以为自定义列类型定义一个事件,然后覆盖自定义单元格的OnContentClick并引发该列的事件。

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.请记住,要使用它,您需要通过代码订阅该事件,因为该事件属于Column ,您无法在设计器中看到它。

Example例子

Here I've created a custom button column which you can subscribe to for its ContentClick event.在这里,我创建了一个自定义按钮列,您可以订阅它的ContentClick事件。 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.这样您就不需要检查DataGridViewCellContentClick事件是否因单击此按钮列而引发。

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);
    }
}

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:要使用它,需要通过代码订阅事件,因为该事件属于Column ,在设计器中是看不到的:

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

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

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