Your answer solves the "problem", but it does not clarify anything. For the sake of knowledge, I'll try to explain what happens briefly (well, it got a little longer than I imagined).
When you create a form from Visual Studio, in add -> new form
, two classes are generated in your project.
Assuming you have created a form called Form1 . Two files will be created: Form1.cs
and Form1.Designer.cs
. The "secret" of everything, is in this second file.
Note that both files declare the same class and both have the reserved word partial
in their signatures. See in the example:
Form1.cs
public partial class Form1 { /*O resto do código é irrelevante agora*/ }
Form1.Designer.cs
public partial class Form1 { /*O resto do código é irrelevante agora*/ }
This indicates that the two files "complement", that is, is the same class divided into two different files. In addition, you can divide the class into as many files as you want. This serves to keep the code more organized, making it possible to separate some responsibilities.
Okay, but what does this have to do with the question?
Visual Studio does this separation to keep all code for creating, positioning, and setting properties / events separate from the code you are about to write. So, in addition to being more organized and you do not need to write your code in the middle of that lot of control manipulation code, Visual Studio can rewrite the file whenever you need it, without fear of spoiling the code already written by you.
Note that in the class constructor (in the file Form1.cs
) the InitializeComponent
method is called, this method is defined in the other file ( Form1.Designer.cs
) and it is responsible for creating and manipulating all controls in form.
This means that everything you create using Visual Studio's visual editor will be replicated in code form to this file and this includes event creation (which happens when a component is double-clicked, or as in your case, by clicking on the events tab and choosing one of them).
When you create an event, whatever Visual Studio creates a method in the main file ( Form1.cs
), following its example:
public static void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("1");
}
and in the Form1.Designer.cs
file, this event is inscribed in the component, thus
dataGridView1.CellDoubleClick += new System.EventHandler(this.dataGridView1_CellDoubleClick);
So, you can create an event "on hand", you just can not leave to inscribe it in the component. This is done by the last block of code I showed, the syntax is basically the following:
controle.NomeDoEvento += new System.EventHandler(nomeDoMetodoQueVaiSerDisparado);