Data Grid View C#背后的正确逻辑

时间:2015-11-06 23:27:32

标签: c# datagridview datagrid

我一直在努力使用dataviewgrid控件大约一周,但没有成功。我想要完成的是检查单元格[0],1,[2]中的空值,并且不允许用户离开行直到它们满足不为空的条件。我已经尝试了许多不同的事件,从单元格验证到行验证和行离开,输入等...我的问题是,如果用户允许说添加名字然后离开行我可以验证数据没有输入到另一个我需要的两个领域。但是,它仍然允许他们在完成输入之前离开该行。我需要一些关于如何检查这个并且不允许用户输入空值的最佳方法的逻辑。这是我拍摄的屏幕截图和一些代码。

enter image description here

因为现在控制是只读的,我有一个按钮来创建一个新条目。我宁愿让用户能够自由编辑,删除和添加他们认为合适的条目。

        private void datagridCustomers_RowEnter(object sender, DataGridViewCellEventArgs e)
    {

        int lastRow = datagridCustomers.Rows.Count - 1;

        datagridCustomers.ClearSelection();

        if (datagridCustomers.Rows[lastRow].Cells[0].Value == null)
        {
            MessageBox.Show("Value can't be null.");
            datagridCustomers.ClearSelection();
            datagridCustomers.Rows[lastRow].Cells[0].Selected = true;
            datagridCustomers.BeginEdit(true);
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以通过首先处理单元格验证事件,检查每个"必需"的EditedFormattedValue来执行此操作。那一排的细胞。 null的单元格将EditedFormattedValue string.Empty

当其中一个指定的单元格为空时,我们可以设置e.Cancel = true并手动将空单元格设置为CurrentCell

public void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex >= 0 && e.ColumnIndex < 3)
    {
        for (int col = 0; col < 3; col++)
        {
            if (string.IsNullOrEmpty(this.dataGridView1[col, e.RowIndex].EditedFormattedValue.ToString()))
            {
                MessageBox.Show("Value can't be null.");
                e.Cancel = true;

                this.dataGridView1.CellValidating -= dataGridView1_CellValidating;
                this.dataGridView1.CurrentCell = this.dataGridView1[col, e.RowIndex];
                this.dataGridView1.BeginEdit(true);
                this.dataGridView1.CellValidating += dataGridView1_CellValidating;
                return;
            }
        }
    }
}

因为我们设置了e.Cancel = true,我们还需要添加以下方法来跳过Form.Closing上的验证:

protected override void WndProc(ref Message m)
{
    switch (((m.WParam.ToInt64() & 0xffff) & 0xfff0))
    {
        case 0xf060:
            this.dataGridView1.CausesValidation = false;
            break;
    }

    base.WndProc(ref m);
}