Reputation: 13215
In a Windows Forms app, there are some things I want various controls of the same type on different forms to always do upon certain events. For example, I want a single click on a DataGridViewCell that is a TextBox-type and is not read only to automatically enter edit mode. The simple event handler code, in this case on a form with a DataGridView called dgvParms
, is:
private void dgvParms_CellClick(object sender, DataGridViewCellEventArgs e) {
DataGridViewCell c = dgvParms[e.ColumnIndex, e.RowIndex];
if (!c.ReadOnly && c is DataGridViewTextBoxCell) {
dgvParms.CurrentCell = c;
dgvParms.BeginEdit(true);
}
}
I could easily move this method to a static class, say CommonEvents
, and then on my individual forms' Load
handlers assign the static method definition to the respective DataGridViews' CellClick event
this.dgvParms.CellClick += CommonEvents.dgvEditOnCellClick;
Is this acceptable or good practice? Or is it preffered to keep event handler logic with each consuming form's code? I could of course do something in between (but redundant) by defining local event handlers which then call the common method, such as
this.dgvParms.CellClick += (a, b) => CommonEvents.dgvEditOnCellClick(a, b);
Upvotes: 1
Views: 126
Reputation: 4502
You could try defining your own customized DataGridView by inheriting from DatagridView, and then adding this and any other specialized behaviors you need. I can't test the code below at this moment, but I believe it is correct:
public class MyDgv : DataGridView
{
protected override void OnCellClick(DataGridViewCellEventArgs e)
{
DataGridViewCell c = this[e.ColumnIndex, e.RowIndex];
if (!c.ReadOnly && c is DataGridViewTextBoxCell)
{
this.CurrentCell = c;
this.BeginEdit(true);
}
}
}
You may have some reason not to do this, but if you like this specific behavior in all of your dgv controls, just use your custom implementation.
Upvotes: 6
Reputation: 70142
This looks absolutely fine to me, although of course you will have to change you code to use the sender
argument to locate the DataGridView
that raised the event:
private void dgvParms_CellClick(object sender, DataGridViewCellEventArgs e) {
DataGridView dgvParams = sender as DataGridView;
DataGridViewCell c = dgvParms[e.ColumnIndex, e.RowIndex];
if (!c.ReadOnly && c is DataGridViewTextBoxCell) {
dgvParms.CurrentCell = c;
dgvParms.BeginEdit(true);
}
}
The general approach of changing or adding behaviour to a control by handling and reacting to its events is called an attached behaviour. It is most typically used in WPF, but there is nothing wrong with using it in WinForms too.
Upvotes: 2