CHRISTOPHER MCCONVILLE CHRISTOPHER MCCONVILLE - 1 month ago 18
C# Question

converting a negative value to 0

I am working with a datagrid view, this datagrid view allows the user to edit cells, I want to set it up so that when a user inserts a negative value, it will convert this value to 0, what would be the best way to code this, i have created the followin code below, it appears to check for negative values, however it does not change the value to zero

if (Convert.ToInt32(dgvDetails.CurrentRow.Cells[2].Value.ToString()) < -0)
{
intQtyInsp = 0;
}
else
{
intQtyInsp = Int32.Parse(row.Cells[2].Value.ToString());

Answer

This will do what you require

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCell currentCell = 
        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
    int cellValue = Convert.ToInt32(currentCell.Value);
    if (cellValue < 0)
        currentCell.Value = 0.ToString();
}

I hope this helps.

Comments