Share via

Extension method for events

Rajkumar Rao 100 Reputation points
2023-10-19T05:53:01.1433333+00:00

Hi experts ,

I was reading a question posted by a user on
https://learn.microsoft.com/en-us/answers/questions/1389629/avoid-code-duplication

and @Karen Payne MVP , suggets the user of creating a extension method. So, I also have a question about the similar topic . The question is what if , in addition of common properties , we want to create a extension method or something like that , for a bunch of events that are common to a normal datagridview and custom datagridview .

some few events which i am interested in are

  protected override bool ProcessCmdKey(ref Message msg, Keys keyData)        
        {
            
                int row = this.CurrentCell.RowIndex;
                int col = this.CurrentCell.ColumnIndex;


 protected override bool ProcessKeyPreview(ref Message m)
        {
  protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
        {


thanks in advance .

Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-10-19T06:44:25.6466667+00:00

    Hi @Rajkumar Rao , Welcome to Microsoft Q&A,

    In the same way you can add events to them.

    But the customized datagridview events are different in the desgin stage.

    You can add the same events as ordinary datagridiview directly after creation.

    The sample code is as follows:

      public static class DataGridViewExtensions
      {
          public static void SetCommonEvents(this DataGridView sender)
          {
              sender.CellClick += CellClickEventHandler;
              sender.EditingControlShowing += EditingControlShowing;
          }
          public static void CellClickEventHandler(object sender, DataGridViewCellEventArgs e)
          {
    
          }
    
          public static void EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
          {
    
          }
      }
    

    Then manually use dataGridView1.SetCommonEvents(); for each one

    Or foreach all datagridview added.

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.