【问题标题】:DataGridView Event to Catch When Cell Value Has Been Changed by User用户更改单元格值时捕获的 DataGridView 事件
【发布时间】:2013-10-23 09:22:50
【问题描述】:

我有一个用 C# 编写的 Winforms 应用程序。

在我的一个 DataGridViews 中,我已将所有列设置为 ReadOnly = true;

我希望应用程序知道用户何时更改了“参考”列中的任何内容,但到目前为止我尝试的所有事件都比用户进行更改时触发的要多得多。例如 CurrentCellChanged 在 DataGridView 最初呈现时触发,并且每次用户只需单击行或沿行等选项卡时触发。

我只对在“参考”列中捕获用户对数据的更改感兴趣,该列是 ReadOnly = false 的唯一列;

为此使用哪个事件最好?

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    CellValueChanged 是你需要的:

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e){
      if(dataGridView1.Columns[e.ColumnIndex].Name == "Reference"){
        //your code goes here
      }
    }
    

    我觉得CellEndEdit的活动也很合你意:

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e){
      if(dataGridView1.Columns[e.ColumnIndex].Name == "Reference"){
        //your code goes here
      }
    }
    

    【讨论】:

    • 我投票支持您的第二个解决方案:private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e){ if(dataGridView1.Columns[e.ColumnIndex].Name == "Reference"){ //your code goes here } },因为每次单元格中的值发生变化时都会触发第一个解决方案,即使用户没有触发该操作。 IE。如果我有一种在后台添加行的方法 CellValueChanged 将触发。
    • 第二个解决方案(CellEndEdit 事件)也会在值未更改时触发 - 例如,即使用户按下“esc”结束编辑而不更改值。
    • @JPProgrammer - 我找到了避免这种情况的方法,请参阅 below 我对 King King 的好答案的补充。
    【解决方案2】:

    在我的例子中,CellValueChanged 事件也在 DGV 初始化时触发,所以我想使用 CellEndEdit,正如 King King 在他的回答中提到的那样。

    为了使King King 的第二个答案更加防弹(见JPProgrammer 的评论),即只做出反应,如果在单元格中输入了值,您可以执行以下操作:

       private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
       {
            int? rowIdx = e?.RowIndex;
            int? colIdx = e?.ColumnIndex;
            if (rowIdx.HasValue && colIdx.HasValue)
            {
                var dgv = (DataGridView)sender;
                var cell = dgv?.Rows?[rowIdx.Value]?.Cells?[colIdx.Value]?.Value;
                if (!string.IsNullOrEmpty(cell?.ToString()))
                {
                    // your code goes here
                };
            };
       }
    

    注意使用?.?[ 运算符处理空值。我已经写了它,以便它可以以更通用的方式使用,但当然您可以添加对“参考”列的检查,只需将上面的内部if 语句替换为以下内容:

           if (dgv.Columns[colIdx.Value].Name == "Reference")
           {
              if (!string.IsNullOrEmpty(cell?.ToString()))
              {
                   // your code goes here
              };
           };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多