如何在C#中检查DataGridView列的值是否为null或0?

时间:2018-06-24 21:30:30

标签: c# if-statement datagridview messagebox

我正在使用c#开发Windows窗体应用程序或书店。此datagridview的作用类似于销售车。数据从sql数据库加载到datagridview。

第1列,第1列,第2列,第3列,第4列和第5列由BookName,ISBN_No,Quantity,UnitPrice,Total和stock组成。当我选择BookName时,ISBN_No和Unit_price将自动填充。我想知道如何检查datagridview单元格值是否包含零或null。我尝试了以下代码。但这没用。

if(Convert.ToInt32(row.Cells[dataGridView1.Columns[5].Index].Value) == 0)
                {
                    MessageBox.Show("Quantiy is not Available");
                }

即使我在此datagridvie单元格中输入零值,也不会显示任何内容。

2 个答案:

答案 0 :(得分:1)

我猜这是尴尬的代码……

Convert.ToInt32(row.Cells[dataGridView1.Columns[5].Index].Value)

可能会让您失望。如果……,Convert.ToInt32将返回零(0)。

row.Cells[dataGridView1.Columns[5].Index].Value

返回null…因此,使用此构造将不会帮助您区分null值和零(0)值,因为两个值都将返回零(0)。

如果FormatException不是有效数字,则代码将引发Value异常。如果值为null,则不会引发异常。

要提供帮助,我相信您需要将此分为三(3)部分。 1)检查一个null值。 2)如果不为空,请检查有效数字。 3)如果该数字有效,请检查该数字是否为零(0)。

if语句的“尴尬”部分是...

dataGridView1.Columns[5].Index  ???

这“总是”将返回“ 5”。因此,声明……

Convert.ToInt32(row.Cells[dataGridView1.Columns[5].Index].Value

可以改写为...

Convert.ToInt32(row.Cells[5].Value

话虽如此,下面的代码将有助于区分空值,非数字值和最后一个零值。正如Derinder所建议的那样,使用int32.TryParse方法是更好的选择。

private void Form1_Load(object sender, EventArgs e) {
  FillGrid();
}

private void FillGrid() {
  for (int i = 0; i < 10; i++) {
    dataGridView1.Rows.Add("C0R" + i, "C1R" + i, "C2R" + i, "C3R" + i, "C4R" + i, i);
  }
}

private void button1_Click(object sender, EventArgs e) {
  DataGridViewRow row = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex];
  if (row.Cells[5].Value != null) {
    if (Int32.TryParse(row.Cells[5].Value.ToString(), out Int32 numvalue)) {
      if (numvalue == 0) {
        MessageBox.Show("Quantity/Value is not null and is equal to zero 0");
      }
      else {
        MessageBox.Show("Quantity/Value is not null, is a valid number but it is NOT equal to zero 0. Its value is: " + numvalue);
      }
    }
    else {
      MessageBox.Show("Quantity/Value is not null but it is not a valid number. Its value is: " + row.Cells[5].Value.ToString());
    }
  }
  else {
    MessageBox.Show("Quantity/Value is null...");
  }
}

答案 1 :(得分:-1)

我认为您可以使用“ int32.TryParse”方法解决您的问题。 另一个好处是,如果不成功,它不会引发类似于convert.toint32的异常。 您总是站在安全的一边。