1

(Beginner's question, if offended please move on, otherwise your input is welcome)

Im trying to invoke datagridview events in Wpf code. Implementing the event calling is straight forward.

for example:

    dgv1.ColumnHeaderMouseClick+=delegate(
    object sender, DataGridViewCellMouseEventArgs e)
{..code on event..};

My question: what is the propper way to invoke the dgv event somewhere else in the code. (press the header column programmatically).

Thank you

2 Answers2

0

A cleaner way for me is to separate the method of of your custom event. Something like this:

private void DataGrid_Sorting(object sender, DataGridSortingEventArgs e)
    {
        MessageBox.Show("Sorting was executed.");
    }

Then set that method to the event property of the control like this:

dataGrid.Sorting += DataGrid_Sorting;

With this code won't get messy and readability is still intact.

I hope it helps you. Happy coding.

tontonsevilla
  • 2,649
  • 1
  • 11
  • 18
0

I think the only "supported" way (that is, not doing something with Windows messages and generally ignoring the .NET framework) would be to call OnColumnHeaderMouseClick. Which is what the method is for, except it's protected because it's really for someone doing their own version of the control, not for any random person to start firing off events.

So you could either subclass DataGridView and add a public method to wrap OnColumnHeaderMouseClick or you could use reflection to call the method even though it's not public.


This is a common pattern in C#. When you write

public event EventHandler XxxEvent;

it turns into something like

private EventHandler _XxxEvent;
public event EventHandler XxxEvent
{
    add { _XxxEvent += value; }
    remove { _XxxEvent -= value; }
}

(plus some handling of null, don't actually use that code as-is).

XxxEvent is not actually a delegate that can be invoked outside the class (you'll get a compiler error "The event 'ClassName.XxxEvent' can only appear on the left hand side of += or -="). And the _XxxEvent backing field is not something you're actually supposed to know about and is private anyway. So if you want anyone to be able to inherit from your class you conventionally have a method whose name is the same as the event prefixed with "On"

protected void OnXxxEvent(EventArgs args)
{
    XxxEvent?.Invoke(this, args);
}
IceGlasses
  • 282
  • 1
  • 4
  • I am getting that the event is out of the current context. I am supplying the correct arg but it seems that the invoking method is wrong. event : DataGridViewCellMouseEventArgs E = new DataGridViewCellMouseEventArgs(col, row, x, y, new System.Windows.Forms.MouseEventArgs(MouseButtons.Left, clicks, x, y, delta)); – ShortCircuit Aug 09 '20 at 15:35