如何防止datagridview在单元格中允许null

如何防止datagridview在单元格中允许null

本文介绍了如何防止datagridview在单元格中允许null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从datagridview输入数据到数据库时,它也允许null ..但我想阻止空值从gridview.in gridview输入数据库我采取有3列的文本框:id,name和city.if i输入id和city,datagridview允许并且不会给出任何错误。所以我的问题是如果用户将单元格设置为空白datagridview不允许用户移动下一个单元格直到该单元格中的用户输入

我尝试过一些代码但不起作用:

when i enter data from datagridview to database it also allow null..but i wanted to prevent null value to enter in the database from gridview.in gridview i take textboxes that have 3 columns:id,name and city.if i enter id and city,datagridview allow that and does not give any error.so my question is if user put the cells blank datagridview does not allow user to move next cell untill user input in that cells
I tried some code but not work like:

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            int i = dataGridView1.Rows.Count;
            for (int j = 0; j < i; j++)
            {


                if (dataGridView1.Rows[j].Cells[0].Value == null)
                {
                    MessageBox.Show("Field 1 is empty");
                }
                else if(dataGridView1.Rows[j].Cells[2].Value == null)
                {
                    MessageBox.Show("Field 2 is empty");

                }
                else if (dataGridView1.Rows[j].Cells[2].Value == null)
                {
                    MessageBox.Show("Field 3 is empty");

                }

            }

        }

推荐答案

private void dataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
{
    // Validate the CompanyName entry by disallowing empty strings.
    if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
    {
        if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
        {
            dataGridView1.Rows[e.RowIndex].ErrorText =
                "Company Name must not be empty";
            e.Cancel = true;
        }
    }
}


这篇关于如何防止datagridview在单元格中允许null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 05:09