将负值转换为0

时间:2012-07-24 12:26:38

标签: c# validation datagridview

我正在使用数据网格视图,这个数据网格视图允许用户编辑单元格,我想设置它以便当用户插入负值时,它会将此值转换为0,这将是最好的编码的方法,我已经创建了下面的跟随代码,它似乎检查负值,但它不会将值更改为零

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

6 个答案:

答案 0 :(得分:2)

这可能是因为dgvDetails.CurrentRow.Cells[2].Value.ToString()row.Cells[2].Value.ToString()可能不是您正在检查的同一个单元格。

答案 1 :(得分:1)

intQtyInsp =Int32.Parse(dgvDetails.CurrentRow.Cells[2].Value.ToString());

if(intQtyInsp < 0)
  {
     intQtyInsp = 0;
  }

答案 2 :(得分:1)

这将满足您的需求

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();
}

我希望这会有所帮助。

答案 3 :(得分:0)

我建议使用扩展方法来确保用户是否输入了一个int。

扩展方法

public static class StringExtension
{
    public static int TryConvertToInt32(this string value)
    {
        int result = 0;
        if (Int32.TryParse(value, out result))
            return result;
        return result;
    }
}

用法

// call the extension method
int intQtyInsp = dgvDetails.CurrentRow.Cells[2].Value.ToString().TryConvertToInt32();

// And check for lower than zero values.
intQtyInsp = intQtyInsp >= 0 ? intQtyInsp : 0;

答案 4 :(得分:0)

int valueFromCell =  Convert.ToInt32(dgvDetails.CurrentRow.Cells[2].Value.ToString());
intQtyInsp = valueFromCell < 0 
               ?  0
               : valueFromCell ;

答案 5 :(得分:0)

if(score < 0) { *score = 0; }
相关问题