【问题标题】:Compare old and new value in DataGridView cell比较 DataGridView 单元格中的新旧值
【发布时间】:2011-08-14 22:29:17
【问题描述】:

如何根据新单元格值是 > 还是

数据是从底层源更新的,可能会被 BindingSource 绑定。

【问题讨论】:

    标签: c# .net datagridview


    【解决方案1】:

    我遇到了类似的问题。我通过使用CellValidating 事件解决了这个问题:

    void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        var oldValue = dgv[e.ColumnIndex, e.RowIndex].Value;
        var newValue = e.FormattedValue;
    }
    

    诚然,我只需要访问旧值,不需要执行任何格式化。不过,我相信您可以通过此事件处理程序应用格式。

    【讨论】:

      【解决方案2】:

      如果 DataGridView 控件的内部源是 DataTable,那么您可以使用 DataRowVersion 枚举来利用旧版本的 DataRow。请注意,我使用了 CellFormatting 事件。

      例子:

      private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
      {
          // if NOT the DataGridView's new row
          if (!this.dataGridView1.Rows[e.RowIndex].IsNewRow)
          {
              // if my desired column
              if (e.ColumnIndex == 0)
              {
                  TestDataSet.TestRow row;
      
                  row = (TestDataSet.TestRow)((DataRowView)this.dataGridView1.Rows[e.RowIndex].DataBoundItem).Row;
      
                  if (row.Column1, (int)row["Column1", DataRowVersion.Original]) > 0)
                          e.CellStyle.ForeColor = Color.Red;
              }
          }
      }
      

      【讨论】:

        【解决方案3】:

        您可能想查看DataGridView.CellValueChangedevent (http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx)。

        如果您想在保存之前检查该值,请查看DataGridView.CurrentCellDirtyStateChanged (http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcelldirtystatechanged.aspx) .

        【讨论】:

          【解决方案4】:

          您可以将单元格的旧值存储在变量中,根据结果比较和更改前景色,然后从变量中删除旧值。

          问候。

          【讨论】:

          • 我希望避免这种情况,因为我需要很多列,但如果没有更简单的方法......
          【解决方案5】:
              private double CuerrLineQty;
              private void GridTransaction_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
              {
                  if (currOp != CurrentOperation.FillDone)
                      return;
          
                  CuerrLineQty = double.Parse(GridTransaction.Rows[e.RowIndex].Cells["DisplayQty"].Value.ToString());
                  
                  CuerrLineQty = double.Parse(GridTransaction.Rows[e.RowIndex].Cells["DisplayQty"].FormattedValue.ToString());
          
                  CuerrLineQty = double.Parse(GridTransaction.Rows[e.RowIndex].Cells["DisplayQty"].EditedFormattedValue.ToString());
          
              }
          

          screenshot

          【讨论】:

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