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



我正在尝试在DataGridView edit中添加一些防弹功能。

列 0、1、2、3、4 必须具有符合数据表主键以及 SQL 表约束的值。

如果任何列为空,

我会在数据表主键上收到内部异常,或者在不可为空的列上收到 SQL 异常。

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

  1. 这是CancelUpdate()的正确行为吗?
  2. 鉴于我既定的目标,我还有其他方法可以实现吗?

.

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

根据LarsTech的建议,我探索并使用了RowValidating事件。 就像将 CancelEventArgs.Cancel 属性设置为 true 一样简单。 ( e.取消 = 真; )

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;

相关内容

  • 没有找到相关文章

最新更新