Search code examples
c#winformsdatagridviewdatagridviewcolumn

How to add a CellContentClick Event per Column in a DataGridView


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

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

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.


Solution

  • 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");