How to use an event from a datagridview that was implemented manually at the end of the Code

1

If I create a DatagridView in this way:

DataTable table = new DataTable();

//DataTable is filled with values here...

DataGridView grid = new DataGridView();

foreach (DataColumn column in table.Columns)
{
grid.Columns.Add(column.ColumnName, column.ColumnName);
}

grid.DataSource = table;

If I want to implement the following event:

private void dataGridView1_EditingControlShowing(object sender, 
DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
{
    TextBox tb = e.Control as TextBox;
    if (tb != null)
    {
        tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
    }
}
}

How do I do ???

Each event represents an independent method that refers to the datagridView, but how do you do this if the datagridview was created at the point of code in the load form method ???

    
asked by jmtaborda 18.12.2018 в 17:40
source

2 answers

2

Although @Pikoh has already answered, and is a correct answer (and more attached to your question), I leave a version that I like more, a slightly shorter version and is using lambda functions:

var grid = new DataGridView();

grid.EditingControlShowing += (s, e) => {
    e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
    if (dataGridView1.CurrentCell.ColumnIndex == 0) 
    {
        // te ahorras una línea si puedes usar c# 7.x
        if (e.Control is TextBox tb)
        {
            tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
        }
    }
};

I like it because the code is not watered everywhere, you go to the constructor and everything is there.

    
answered by 18.12.2018 / 19:38
source
2

To add an event handler, the operator += is used. For example, in your case it would be like this:

grid.EditingControlShowing += dataGridView1_EditingControlShowing; 

after creating the grid.

More information: Subscribe and unsubscribe to events :

  
  • Define an event handler method whose signature matches the delegate signature of the event.
  •   
  • Use the sum and assignment operator ( += ) to associate the event handler with the event.
  •   
        
    answered by 18.12.2018 в 17:48