简体   繁体   中英

How to determine if there are any event handlers for DataGridView.CellFormatting event?

I'm writing a control which inherits from a DataGridView. One of the things I would like to do is to handle the bug whereby a column's format provider is not used without handling the CellFormatting event (and doing the formatting myself) .

I thought I would write an "OnCellFormatting" method which says "if there's a column format provider, and there's no CellFormatting event handler(s), do the formatting" .

The important bit (I thought) was "...and there's no CellFormatting event handler" .

Now, in the past when I've written controls with events, I've done something like this:

  public event EventHandler SomethingHappened;

  protected void OnSomethingHappened(EventArgs e)
  {
     EventHandler handler = this.SomethingHappened;
     if (handler != null) handler(this, e);
  }

This works fine and my understanding is that this pattern determines if handlers are attached to the event and, if so, invoke those handlers. Fair enough, but why can't I do this:

  protected void OnCellFormatting(EventArgs e)
  {
     EventHandler handler = this.CellFormatting;
     if (handler == null) DoSomething();
  }

The error is "The event 'System.Windows.Forms.DataGridView.CellFormatting' can only appear on the left hand side of += or -="

What's different about this (type of) event ?

If I go to the definition of the event, and create my own, ie.

public event DataGridViewCellFormattingEventHandler CellFormatting2

...the compiler is quite happy to assign this to my "handler" variable, so my question is - what's different with the CellFormatting event (and, one presumes, many others) that I cannot determine if there are any event handlers for it ?

Thanks, Ross

Only the class that declares the event has full access to it.

For instance, you cannot invoke an event from other classes - even derived ones.

You are in this situation, because you are deriving from DataGridView .


You may be able to use reflection:

How do I raise an event via reflection in .NET (c#)?

MSDN: Type.GetEvent Method

That shows the assignment can't be performed because it's read only. May be you can try declaring the handler private?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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