Observe the event created with the Winforms UserControl instance

In my winforms application, I have a UserControl that contains a DataGridView. I instantiate and load this UserControl when needed into a panel in my main form (frmMain). My problem is how to edit or listen to events raised in my UC DataGridView. For example, I want to handle the CellDoubleClick event of the DataGridView in my main form, not via UC.

Is it possible? I thought about updating a property when a cell in the grid was double clicked and then let my main form do something when that property changes, so I thought about using INotifyPropertyChanged. However, I have not gone into great detail on how to use it in the m script, and would deeply appreciate some help in this regard, or might suggest an alternative solution.

Hence, more than x!

+2


source to share


2 answers


Thank u 4 for your reply. Sorry I didn't reply earlier. I managed to sort out this problem by creating a public event in my UC:

public event DataGridViewCellEventHandler GridRowDoubleClick {
    add { dgvTasks.CellDoubleClick += value; }
    remove { dgvTasks.CellDoubleClick -= value; }
}

      

and in my main form , after creating and loading UC

_ucTask.GridRowDoubleClick += new DataGridViewCellEventHandler(TasksGrid_CellDoubleClick);

      



with the following nested event:

private void TasksGrid_CellDoubleClick( object sender, DataGridViewCellEventArgs e ) {
    // do work here!
}

      

This works, although I don't know if any of you experts foresee such an approach.

+2


source


The custom control has to encapsulate some logic, so if you want to handle the DataGridView event that is in your control as you described, you probably missed something about the idea of ​​custom controls and encapsulation. Technically, there are two ways to do it:

  • Make a public property in your custom DataGridView control.
  • Make an event wrapper. You will need to create an event in your custom control that fires when the DataGridView CellDoubleClick (or any) is terminated, and in your code behind you will handle this event wrapper.


The second approach is more logical, since the internal logic of your control is encapsulated, and you can provide the end user of your component with a more logical and meaningful event, then CellDoubleClidk or else.

+2


source







All Articles