DataGridView捕获用户行选择

Ras*_*dit 11 c# winforms

我在处理选择时遇到问题DataGridView.我的网格视图包含金额列.表单上有一个文本框,它应显示所选网格视图行的总量.因此,当用户选择/取消选择gridview行并相应地计算(加/减)量时,我需要捕获事件.我找到了两种方法:

  1. 使用RowEnterRowLeave事件.当用户选择/取消选择单行时,这些工作正常.但是,当用户一次选择多行时,该事件仅针对最后一行触发.因此,从我的总金额中,只添加/减去最后一行中的金额.从而使我的结果错误.

  2. 使用该RowStateChanged事件.这适用于多行.但是,如果用户滚动数据网格,事件将被触发事件.

有谁处理过这种情况.我想知道我应该使用哪个datagrid事件,以便我的代码仅在用户选择/取消选择包含多行的行时执行.

Ras*_*dit 22

找到了解决方案.我RowStateChanged只能StateChanged在行中使用并运行我的代码Selected...

private void dgridv_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
    // For any other operation except, StateChanged, do nothing
    if (e.StateChanged != DataGridViewElementStates.Selected) return;

    // Calculate amount code goes here
}
Run Code Online (Sandbox Code Playgroud)


小智 6

我认为您可以考虑 SelectionChanged 事件:

private void DataGridView1_SelectionChanged(object sender, EventArgs e) {
  textbox1.Text = DataGridView1.SelectedRows.Count.ToString();
}
Run Code Online (Sandbox Code Playgroud)


Kiq*_*net 6

我使用SelectionChanged事件或CellValueChanged事件:

        dtGrid.SelectionChanged += DataGridView_SelectionChanged;
        this.dtGrid.DataSource = GetListOfEntities;
        dtGrid.CellValueChanged += DataGridView_CellValueChanged;


    private void DataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        DataGridViewRow row = dtGrid.Rows[e.RowIndex];
        SetRowProperties(row);
    }

    private void DataGridView_SelectionChanged(object sender, EventArgs e)
    {
        var rowsCount = dtGrid.SelectedRows.Count;
        if (rowsCount == 0 || rowsCount > 1) return;

        var row = dtGrid.SelectedRows[0];
        if (row == null) return; 
        ResolveActionsForRow(row);
    }
Run Code Online (Sandbox Code Playgroud)