简体   繁体   English

当DataGridView ButtonColumn单击时

[英]when DataGridView ButtonColumn Clicked

i have a dataGridView in my form , and i have a colum of button in it. 我的表单中有一个dataGridView,并且其中有一个按钮列。 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. 我试图在代码下面写werite,但是当我单击列标题时,将执行块中的写入代码。 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 !");
            }
        }
    }
}

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. 更新:我忘记了您必须检查ColumnIndex:如果用户单击标题行,则ColumnIndex的值为-1,因此UpDatedataGridView2.Columns [e.ColumnIndex]引发异常。 To summarize, the final checks should look like this: 总而言之,最终检查应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM