His answer solves the "problem", but does not clarify anything. For knowledge purposes, I’ll try to explain to you what happens very briefly (well, it’s a little longer than I imagined).
When you create a form through Visual Studio, in add -> new form
, two classes are generated in your project.
Suppose you 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 the two files declare the same class and both have the reserved word partial
in your 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 each other", ie, is the same class divided into two different files. Even, you can split the class into as many files as you want. This serves to keep the code more organized, making possible the separation of some responsibilities.
Okay, but what does that have to do with the question?
Visual Studio makes this separation to keep all the code creation, positioning and definition of properties/events separate from the code you will write. So in addition to being more organized and you don’t have to write your code in the middle of that lot of code handling controls, Visual Studio can rewrite the file whenever you need, without fear of ruining the code you’ve already written.
Note that in the class constructor (in the file Form1.cs
) is called the method InitializeComponent
, this method is defined in the other file (Form1.Designer.cs
) and he’s responsible for creating and manipulating all the controls in the form.
This means that everything you create using the visual editor of Visual Studio will be replicated in code form to this file and this includes event creation (what happens when you double-click on a component or, as in your case, click on the events tab and choose one of them).
When you create an event, whatever it is, Visual Studio creates a method in the main file (Form1.cs
), following his example:
public static void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("1");
}
and in the archive Form1.Designer.cs
, this event is inscribed in the component, in this way
dataGridView1.CellDoubleClick += new System.EventHandler(this.dataGridView1_CellDoubleClick);
So you can create an event "at hand", just don’t forget to enter it into the component. This is done by the last block of code I showed, and the syntax is basically the following:
controle.NomeDoEvento += new System.EventHandler(nomeDoMetodoQueVaiSerDisparado);
If you click on the value contained in the cell, the result will be null because the message is commented, but if you click on the cell after the content, the second function will be called and the result will be as expected.
– Vanderlei