【问题标题】:Clicking a button on a DataGridView Cell Button triggers all the cell button commands in the row单击 DataGridView 单元格按钮上的按钮会触发该行中的所有单元格按钮命令
【发布时间】:2015-09-25 20:55:06
【问题描述】:

我有一个 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);
    }
}

【问题讨论】:

  • 难怪......你的两个条件都是真的,它总是会显示两个消息框。试试下面@Eric 给出的解决方案。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# winforms datagridview


【解决方案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)
....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-15
    • 2021-05-03
    • 1970-01-01
    • 2011-09-16
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多