当DataGridView ButtonColumn单击时

时间:2013-10-30 12:40:49

标签: c# events button datagridview datagridviewcolumn

我的表单中有一个dataGridView,我有一个按钮列。我只想在点击其中一个buttoms时执行一些代码。我试图在代码下面做werite但是当我点击列的标题时,执行了块中的写入代码。 是帮助我的人吗?

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 !");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

添加以下检查:

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

第一个条件检查用户是否单击了属于按钮列的单元格,而第二个条件检查是否连续发生了单击。

更新:我忘了你必须检查ColumnIndex:如果用户点击标题行,ColumnIndex的值为-1,因此UpDatedataGridView2.Columns [e.ColumnIndex]会抛出异常。总而言之,最终检查应如下所示:

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