【问题标题】:Commit DataGridView cell edit only when a certain key is pressed仅在按下某个键时提交 DataGridView 单元格编辑
【发布时间】:2011-05-15 13:32:32
【问题描述】:

我有一个附加到 XML 数据源的 DataGridView。每次用户编辑单元格时,程序都会自动更新相关的 XML 文件。为了处理编辑,我同时使用:

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
       //do edit
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
       //do edit
}

编辑工作就是这样,用户点击一个单元格并更改值。然后他应该按下 Enter 键以使一切正常,但是例如,如果他在外面单击鼠标按钮,或者如果他用左箭头键走出单元格,程序就会出错。无论如何它都可以工作,因为我设法处理了这个异常,但我希望我的程序能够更好地处理这种情况。例如,当用户输入一个单元格时,我想拒绝他使用箭头键继续进入其他单元格。我试图捕捉KeyDown 事件,但没有成功:

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if ((e.KeyCode == Keys.Left) || (e.KeyCode == Keys.Right)) //etc...
        {
            e.Handled = true;
        }
    }

基本上,当开始编辑时,我只想在用户按下 Enter 时编辑单元格。有任何想法吗?如果控件(在本例中为单元格)在编辑期间失去焦点(用户按下 Esc,在控件外单击鼠标等...)我需要防止 EndEdit 事件开始。

【问题讨论】:

标签: c# .net winforms datagridview


【解决方案1】:

您可以使用 RowValidating 事件来取消事件,并使用 RowValidated 事件来保存,如下所示:

    private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
    {
        string data = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        if(!ValidateData(data))
            e.Cancel = true;
    }

    private bool ValidateData(string data)
    {
        // do validation which u want to do.
    }

    private void dataGridView1_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
        string data = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        SaveData(data);
    }

    private void SaveData(string data)
    {
        // save data
    }

【讨论】:

  • 这如何确保在按下 Enter 键时仅保存编辑?问题不在于验证输入的数据。
  • ValidateData 是什么意思?对我来说,任何价值都是好的,我只是想防止用户走出选定的单元格。我应该如何处理 ValidateData?
【解决方案2】:

宁可使用RowValidating 事件,它允许您在数据无效的情况下取消操作。

【讨论】:

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