CancelEdit()传递不需要的控件。我还可以做些什么?

时间:2014-12-15 19:57:34

标签: c# datagridview sqlconnection

我试图在DataGridView edit中添加一些防弹。

第0,1,2,3,4列必须具有符合数据表主键和SQL表约束的值。

如果任何列为空,我会在数据表主键上获得内部异常,或在非可空列上获得SQL异常。

LeaveRow事件中,如果任何列值为空,我会调用CancelUpdate()。问题是当CancelUpdate()执行时,它将控制权传递给事件的顶部并重新开始。

  1. 这是CancelUpdate()的正确行为吗?
  2. 鉴于我的既定目标,我还有另一种方法可以完成吗?
  3. private void dgvVX130_LeaveRow(object sender, DataGridViewCellEventArgs e)
    {      
        bool z = true; // <======= CancelUpdate() passes execution to here
        switch (dgvVX130.CurrentCell.ColumnIndex.ToString())
        {
            case "0":
                if (dgvVX130.IsCurrentRowDirty && 
                    (dgvVX130.CurrentRow.Cells[1].Value.ToString() == "" || 
                    dgvVX130.CurrentRow.Cells[2].Value.ToString() == "" || 
                    dgvVX130.CurrentRow.Cells[3].Value.ToString() == ""))
                {
                    z = false;
                    dgvVX130.CancelEdit(); // <=== Passes execution to top of event
                    MessageBox.Show("You must have Database, Schema, and TableName " +
                        "defined before leaving row"); // <===== Doesn't get executed
                }
                break;
            case "1":
                // Additional code is irrelevant
                break;
        }
    }
    

1 个答案:

答案 0 :(得分:1)

采用LarsTech建议我探索并使用了RowValidating事件。就像将CancelEventArgs.Cancel属性设置为true一样简单。 (e.Cancel = True;)

private void dgvVX130_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            switch (dgvVX130.CurrentCell.ColumnIndex.ToString())
            {
                case "0":
                    if (dgvVX130.IsCurrentRowDirty && (dgvVX130.CurrentRow.Cells[1].Value.ToString() == "" 
                        || dgvVX130.CurrentRow.Cells[2].Value.ToString() == "" 
                        || dgvVX130.CurrentRow.Cells[3].Value.ToString() == ""))
                    {
                        e.Cancel = true;
                        MessageBox.Show("You must have Database, Schema, and TableName defined before leaving row");
                    }
                    break;
                case "1":
                    if (dgvVX130.IsCurrentRowDirty && (dgvVX130.CurrentRow.Cells[0].Value.ToString() == "" 
                        || dgvVX130.CurrentRow.Cells[2].Value.ToString() == "" 
                        || dgvVX130.CurrentRow.Cells[3].Value.ToString() == ""))
                    {
                        e.Cancel = true;
                        MessageBox.Show("You must have Database, Schema, and TableName defined before leaving row");
                    }
                    break;