How to add a CellContentClick Event per Column in a DataGridView

梦想的初衷 提交于 2019-12-04 18:24:37
Reza Aghaei

You can define an event for the custom column type, then override OnContentClick of the custom cell and raise the event of the 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.

Example

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

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");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!