簡體   English   中英

接受DataGridView中的新行,而無需手動更改其值

[英]Accept new row in DataGridView without manually changing its value

我有一個數據databound DataGridView 要插入新行,我需要處理DefaultValuesNeeded

新行將顯示我分配的值。 到這里為止一切正常。

目前,該行尚未附加到基礎DataTable 沒關系

接受新行的唯一方法是將任何單元格設置為編輯模式,然后更改
值並關閉編輯器。
現在,將新行添加到DataTable

我的問題是我想用最少的用戶輸入來添加行。
如果用戶確定值合適,則他/她應該能夠確認
而不更改某些單元格值(並將它們設置回原始值)

有沒有一種方法可以做到這一點,例如通過按回車鍵 ,捕獲命令和強制
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;
        }
    }
}

我的建議是,您可以使用CellValidating Even t和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;
                }
            }
        }
    }

我找到了解決方案。
我必須將單元格狀態設置為臟,然后進入編輯模式。 否則在選擇另一行時內部狀態將被破壞

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;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM