单击DataGridView单元格按钮上的按钮将触发行中的所有单元格按钮命令

时间:2015-07-08 05:38:28

标签: c# winforms datagridview

我有一个包含9列的DataGridView。列索引4和8是单元格按钮。当我点击按钮索引4时,它将执行给定的命令,但也将执行为按钮索引8给出的命令。无论哪种方式按钮我单击(4或8)它将始终执行动作1然后动作2

private void dgvItems_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    var senderGrid = (DataGridView)sender;

    if (senderGrid.Columns[4] is DataGridViewButtonColumn && senderGrid.Rows[e.RowIndex] is DataGridViewRow)
    {
         MessageBox.Show("ACTION 1: Column index is " + e.ColumnIndex + "; Row Index " + e.RowIndex);
    }

    if (senderGrid.Columns[8] is DataGridViewButtonColumn && senderGrid.Rows[e.RowIndex] is DataGridViewRow)
    {
         MessageBox.Show("ACTION 2: Column index is " + e.ColumnIndex + "; Row Index " + e.RowIndex);
    }
}

1 个答案:

答案 0 :(得分:1)

只需按e.ColumnIndex检查当前列。将if条件更正为:

if (e.ColumnIndex == 4)
    MessageBox.Show("ACTION 1: Column index is " + e.ColumnIndex + "; Row Index " + e.RowIndex);

if (e.ColumnIndex == 8)
....