简体   繁体   English

错误检查列值是否为空或空

[英]Error checking if column value is empty or null

I am trying to check if the column value ["CellNumber"] is emtpy or not with if condition. 我正在尝试检查列值["CellNumber"]是否为空,如果满足条件。 Even if the column cell value is not empty, it is prompting with message box instead of exit the foreach loop and updating the data. 即使列单元格值不为空,它也会在消息框提示而不是退出foreach loop并更新数据。

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        da = new SqlDataAdapter("select * from Measurement", con);
        SqlCommandBuilder cb = new SqlCommandBuilder(da);
        foreach (DataGridViewRow row in dgv.Rows)
        {
            if (Convert.ToString(row.Cells["CellNumber"].Value) == "")
            {
                MessageBox.Show("Please enter cellnumber", "Missing Information");
                return;
            }
        }
        try
        {
            da.Update(ds, "Measurement");
        }
        catch (DBConcurrencyException ex)
        {
            MessageBox.Show(ex.Message);
        }

Please check your number of rows in datagridview by doing 请通过执行以下操作检查datagridview中的行数:

 DataGridView. If myDataGridView.Rows.Count == 0

If it is equal to 0 then it is empty 如果等于0,则为空

您使用字符串“ CellNumber”,难道不是int吗?

if (Convert.ToString(row.Cells["CellNumber"].Value) == "")

if (string.IsNullOrEmpty(row.Cells["CellNumber"].Value))
{ Your Code  }

Try this way 试试这个

if (row.Cells["CellNumber"].Value == null || string.IsNullOrEmpty(row.Cells["CellNumber"].Value.ToString()))
{
   //rest
}

call dgv.CurrentRow.DataGridView.EndEdit(); 调用dgv.CurrentRow.DataGridView.EndEdit(); to save changes in all cells before validating :) 在验证之前保存所有单元格中的更改:)

private void btnUpdate_Click(object sender, EventArgs e)
{
    dgv.CurrentRow.DataGridView.EndEdit();
    dgv.EndEdit();
    ....

try to use the .EditedFormattedValue 尝试使用.EditedFormattedValue

        if (string.IsNullOrWhiteSpace(row.Cells["CellNumber"].EditedFormattedValue.ToString()))
        {
            MessageBox.Show("Please enter cellnumber", "Missing Information");
            return;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM