【问题标题】:Accept new row in DataGridView without manually changing its value接受 DataGridView 中的新行而不手动更改其值
【发布时间】:2013-01-28 18:03:51
【问题描述】:

我有一个 databound DataGridView。 要插入新行,我处理 DefaultValuesNeeded

新行显示我分配的值。到这里为止一切正常。

此时该行尚未附加到基础DataTable没关系

接受新行的唯一方法是将任何单元格设置为编辑模式,更改
值并关闭编辑器。
现在新行被添加到DataTable

我的问题是我想以最少的用户输入添加行。
如果用户认为这些值没问题,他/她应该能够确认
不更改某些单元格值(并将它们设置回原始值)

有没有办法实现这一点,例如按enter,捕获命令并强制
DataGridView 是否与单元格值更改一样?

我已经尝试更改 dgv_KeyDown() 中的值但没有成功。
有什么建议吗?

private void dgv_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        if (dgv.CurrentCell != null && dgv.CurrentCell.OwningRow.DataBoundItem == null)
        {
            //ToDo: Accept the new row

            e.Handled = true;
        }
    }
}

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:

    我找到了解决方案。
    我必须将单元格状态设置为脏并进入编辑模式。否则在选择另一行时内部状态将被破坏

    private void dgv_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            if (dgv.CurrentCell != null && dgv.CurrentCell.OwningRow.DataBoundItem == null)
            {
                dgv.NotifyCurrentCellDirty(true);
                dgv.BeginEdit(true);
                e.Handled = true;
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      我的建议是,你可以使用CellValidating Event 和RowValidating Event 来完成这个任务。

          private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
          {
              if (dataGridView1.IsCurrentCellDirty) //or IsCurrentRowDirty
              {
                  if (e.ColumnIndex == 1)
                  {
                      if (MessageBox.Show("You're about to change the value. Do you want to continue?\n\nPress ESC to cancel change.",
                                          "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information) != System.Windows.Forms.DialogResult.OK)
                      {
                          e.Cancel = true;
                      }
                  }
              }
          }
      

      【讨论】:

      • 这不是我打算做的。我想将未附加喷射的行添加到我的数据源中,并且不阻止更改值。
      猜你喜欢
      • 2016-08-09
      • 2012-09-28
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多