2013年11月14日 星期四

[除錯] 因為程式無法認可或結束儲存格值的變更

情況:
承自 DataGridView 的擴展控項 myDataGridView
當CellValidating...沒過...Coding為e.cancel=true;
則程式最先進入控項的ProcessDialogKey...
當Cdoing為base.CurrentCell = base.Rows[base.CurrentCell.RowIndex].Cells[nextColumn.Index];
便會出現錯誤訊息「因為程式無法認可或結束儲存格值的變更」
所以要改寫以下...(紅色+判斷)
        protected override bool ProcessDialogKey(System.Windows.Forms.Keys keyData)
        {
            //MessageBox.Show(this.CurrentCell.RowIndex.ToString());
            if (keyData == Keys.Tab || keyData == Keys.Enter)
            {
                if ((base.CurrentCell == null))
                {
                    return true;
                }
                DataGridViewColumn nextColumn = null;
                nextColumn = base.Columns.GetNextColumn(base.Columns[base.CurrentCell.ColumnIndex], DataGridViewElementStates.Visible, DataGridViewElementStates.ReadOnly);
                if ((nextColumn != null))
                {
                    if(this.CurrentCell.IsInEditMode)
                        //當驗證沒過時, Coding部份為e.cancel=true, 使用這個方式就不會出錯了!
                        return base.ProcessDialogKey(Keys.Tab); 
                    else
                        base.CurrentCell = base.Rows[base.CurrentCell.RowIndex].Cells[nextColumn.Index];

                }
                else
                {
                    nextColumn = base.Columns.GetFirstColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.ReadOnly);
                    if ((base.CurrentCell.RowIndex + 1) == base.Rows.Count)
                    {
                        base.CurrentCell = base.Rows[0].Cells[nextColumn.Index];
                    }
                    else
                    {
                        if (this.CurrentCell.IsInEditMode)
                            //當驗證沒過時, Coding部份為e.cancel=true, 使用這個方式就不會出錯了!
                            return base.ProcessDialogKey(Keys.Tab); 
                        else
                            base.CurrentCell = base.Rows[base.CurrentCell.RowIndex + 1].Cells[nextColumn.Index];
                    }
                }
                //MessageBox.Show(this.CurrentCell.RowIndex.ToString());
                return true;
            }
            return base.ProcessDialogKey(keyData);
        }

參考:
[C#]DataGridView欄位驗證只能是數字且不能為空白
DataGridView.Rows.Clear() raise exception 
You received exception message Exception.InvalidOperation "Operation did not succeed because the program cannot commit or quit a cell value change." . If this DataGridView cell is in edit mode, you have to end/submit edit and then continue.

DataGridView 控制項 (Windows Form)