1

FYI, I looked at existing postings and I did not find exactly what I needed.

I am using Visual Studio 2008 to write a C# Windows Forms program. I have a DataGridView object that displays data from a table. When a user clicks on a cell I want to be able to grab the contents of that cell.

How do get an action to take place whenever there is a click on any cell in the datagridview. If the user clicks on the same cell 5 times in a row, I want the action to happen five times.

I am not even sure what the name of the event handler would be.

I tried the following, but it didn't work.

This was the code on the FormName.cs file:

private void DATASOURCEDataGridView_CellContentClick(object sender, 
           DataGridViewCellEventArgs e)
{
    MessageBox.Show("clicked");
}

This was the code on the FormName.Designer.cs File:

this.DATASOURCEDataGridView.CellContentClick += 
    new System.Windows.Forms.DataGridViewCellEventHandler(
        this.DATASOURCEDataGridView_CellContentClick);

Thanks for the help!

3
  • Nothing happens when I click on a cell in the datagridview. I would expect to see the messagebox pop up. Commented Jun 11, 2009 at 6:30
  • See my answer about moving the EventHandler from the designer file to your main .cs file. I've only used my code with ButtonCells, so it's possible you may have to use the CellClick Alex mentions in his answer. Commented Jun 11, 2009 at 6:39
  • Sorry, ignore my previous comment, turns out I was wrong. I deleted my answer so no one is led astray :) Commented Jun 11, 2009 at 6:47

1 Answer 1

1

Use the CellClickedEvent:

 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
          MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
        }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Alex, this was exactly what I needed. I needed to use CellClick instead of CellContentClick. Problem solved! Much appreciated!!!
FYI to anyone else using this code. It still needs one modification. If the user clicks on the column header or row header there is a column or row out of range error. You just need to add some additional logic to handle that scenario and it works great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.