Hooking up an event - which is what you are doing here:
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
}
And here:
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.CellMouseClick += dataGridView1_CellMouseClick;
}
Does not cause the event to be fired - it just adds a method to the collection of handlers which will be called when the event does fire. So repeatedly adding the handler in your button Click handler doesn't help anything: each time your user presses the button, it will add another handler so when the event finally fires, it will call the same handler method a number of times.
You should only add the handler once, under normal circumstances.
And you shouldn't be trying to "force" events - instead, restructure your code so that the code inside your CellMouseClick handler is in a separate method, and call that from both your click events:
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
dataGridView1.CellMouseClick += dataGridView1_CellMouseClick;
}
private void button1_Click(object sender, EventArgs e)
{
DoMyClickAction();
}
void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right && e.RowIndex == -1 && e.ColumnIndex == -1)
{
DoMyClickAction(e.X, e.Y);
}
}
private void DoMyClickAction(int x = 0, int y = 0)
{
mCheckedListBox.Items.Clear();
foreach (DataGridViewColumn c in dataGridView1.Columns)
{
mCheckedListBox.Items.Add(c.HeaderText, c.Visible);
}
int PreferredHeight = (mCheckedListBox.Items.Count * 16) + 7;
mCheckedListBox.Height = (PreferredHeight < MaxHeight) ? PreferredHeight : MaxHeight;
mCheckedListBox.Width = this.Width;
mPopup.Show(dataGridView1.PointToScreen(new Point(x, y)));
}