I am guessing that the awkward line of code…
Convert.ToInt32(row.Cells[dataGridView1.Columns[5].Index].Value)
may be throwing you off. The Convert.ToInt32
is going to return zero (0) if…
row.Cells[dataGridView1.Columns[5].Index].Value
returns null… therefore, using this construct is not going to help you distinguish between a null
value and a zero (0
) value as BOTH values will return zero (0).
The code WILL throw a FormatException
exception if Value
is not a valid number. It will NOT throw an exception if the value is null.
To help, I am confident you will need to break this down to three (3) parts.
1) Check for a null
value.
2) If not null, check for a valid number.
3) If the number is valid, check if it is zero (0).
The “awkward” portion of the if
statement is…
dataGridView1.Columns[5].Index ???
this is “always” going to return “5”. Therefore, the statement…
Convert.ToInt32(row.Cells[dataGridView1.Columns[5].Index].Value
could be rewritten as…
Convert.ToInt32(row.Cells[5].Value
With that said, below is the code that will help distinguish between null values, non-number values and lastly if the value is zero. As Derinder suggest, using the int32.TryParse
method is a better option.
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...");
}
}