OnClick event in WinForms DataGridView

eomeroff picture eomeroff · Jan 31, 2010 · Viewed 17.2k times · Source

I am using DataGridView in WinForms and by this piece of code I am assigning it columns and values

dataGrid.DataSource = sourceObject;

only by this line all the columns and values into the grid. How do I handle the onClick event of a specific row or field. I want to do edit a particular item in the grid but I cannot find any way to send the id of an item from the event method.

There is class DataGridViewEventHandler which I do not understand?

I have also tried to add columns manually as a buttons but I did not find way to assign it action method onClick.

Answer

Asad picture Asad · Jan 31, 2010

You cannot find "OnClick" event for cell inside DataGridView, as it does not exist. Have a look at MSDN Page for DataGridView Events provided for Cell Manipulation and Events

Here are some samples from MSDN, about the events which you may use

Sample CellMouseClick Event and Handler

   private void DataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)    {

    System.Text.StringBuilder cellInformation = new System.Text.StringBuilder();
    cellInformation .AppendFormat("{0} = {1}", "ColumnIndex", e.ColumnIndex );
    cellInformation .AppendLine();
    cellInformation .AppendFormat("{0} = {1}", "RowIndex", e.RowIndex );
    cellInformation .AppendLine();
    MessageBox.Show(cellInformation.ToString(), "CellMouseClick Event" );
}

Sample CellClick Event and Handler

private void dataGridView1_CellClick(object sender,
    DataGridViewCellEventArgs e)
{

    if (turn.Text.Equals(gameOverString)) { return; }

    DataGridViewImageCell cell = (DataGridViewImageCell)
        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

    if (cell.Value == Play)
    {
        // PlaySomething()
    }
    else if (cell.Value == Sing)
    {
        // SingSomeThing();
    }
    else 
    {
     MessagBox.Show("Please Choose Another Value");
    }
}

Hope this helps