0

I am having trouble getting my application to work correctly. I am trying to select a row in a datagridview with the mouse. I need to save the index of this row to allow me to navigate around the selected row.

I have been looking at DataGridView.CellMouseClick Event (Link) But I am unable to ensure that the event handler is associated with the CellMouseClick event.

My code for this so far is simple, Im just trying to see if its detecting mouse clicks:

    public event DataGridViewCellMouseEventHandler CellMouseClick;

    private void DataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)
    {
        MessageBox.Show("Mouse clicked in the datagridview!");
    }

Can anyone point out where I may be going wrong. Any help would be great!

Daniel Flannery
  • 1,166
  • 8
  • 23
  • 51

1 Answers1

6

You need to "wire up" the event.

If your DataGridView is called DataGridView1 then you need the following line of code in either the constructor for your form, the designer (if you add the event handler via the designer) or in the Load event:

DataGridView1.CellMouseClick += DataGridView1_CellMouseClick;

This attaches the event handler in your code to the event.

Your current sample looks like this:

    public event DataGridViewCellMouseEventHandler CellMouseClick;

    private void DataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)
    {
        MessageBox.Show("Mouse clicked in the datagridview!");
    }

There is no need to redeclare the event (public event DataGridViewCellMouseEventHandler CellMouseClick;) unless you are building your own user control that will host a DataGridView and you effectively want to "wrap" or "rebroadcast" that event.

Community
  • 1
  • 1
dash
  • 89,546
  • 4
  • 51
  • 71