Pregunta

i have a dataGridView in my form , and i have a colum of button in it. i want execute some code when only one of the buttoms clicked. i tried to do werite below code but when i clicked of the header of the columns, the writed code in block executed. is the any one to help me ?

private void UpDatedataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
    MessageBox.Show(UpDatedataGridView2.CurrentCellAddress.ToString());

    if (UpDatedataGridView2.RowCount > 0)
    {
        if (UpDatedataGridView2.CurrentCell.Value.ToString().Trim() == "delete Record")
        {
            if (DialogResult.Yes == MessageBox.Show("Are you sure to delete the record", "Delete", MessageBoxButtons.YesNo))
            {
                UpDatedataGridView2.ReadOnly = false;
                UpDatedataGridView2.AllowUserToDeleteRows = true;
                string number = UpDatedataGridView2.CurrentRow.Cells[1].Value.ToString();
                da.DeleteCommand.CommandText = "Delete from tblKala where ID =" + number;
                conn.Open();
                da.DeleteCommand.ExecuteNonQuery();
                conn.Close();
                dataGridView1.ReadOnly = true;
                UpDatedataGridView2.DataSource = SelectData();
                MessageBox.Show("Deleting done !");
            }
        }
    }
}
¿Fue útil?

Solución

Add the following checks:

if (UpDatedataGridView2.Columns[e.ColumnIndex] is
    DataGridViewButtonColumn &&
    e.RowIndex != -1)

The first condition checks if a user clicked on the cell which belongs to a button column, while the second checks if the click happened in a row.

UPDATE: I forgot you have to check the ColumnIndex: if a user clicks on the header row, ColumnIndex has the value -1 and therefore UpDatedataGridView2.Columns[e.ColumnIndex] throws an exception. To summarize, the final checks should look like this:

if (e.ColumnIndex != -1 &&
    e.RowIndex != -1 && UpDatedataGridView2.Columns[e.ColumnIndex] is
    DataGridViewButtonColumn )
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top