无效的强制转换异常。从数字转换时,该值必须小于无穷大的数字

时间:2015-05-18 15:06:42

标签: c# gridview

我在这一行收到了无效的强制转换

b =(int)dataGridView2.Rows [e.RowIndex] .Cells [4] .Value;

下面是我的代码

    private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {

 int a, b;
    if (dataGridView2.Rows.Count > 0 && e.RowIndex >= 0 && e.ColumnIndex >= 0)
    {
        a = (int)dataGridView2.Rows[e.RowIndex].Cells[2].Value;
        b = (int)dataGridView2.Rows[e.RowIndex].Cells[4].Value;
        if (b > a)
        {
            MessageBox.Show("required quantity exceeds stock");
        }
    }

}

1 个答案:

答案 0 :(得分:0)

NullReferenceException是由于传递的RowIndex索引值在某些情况下可能无效。在这种情况下,dataGridView2.Rows[e.RowIndex]将注定要使用空引用...

InvalidCastException可能是由于隐式投射造成的,这是你考虑的。您没有提及datagridview单元格的内容,但如果在这种情况下逻辑上可以进行转换,则最好考虑Convert.ToInt32()方法的静态转换...

最后,下面的代码段可能会解决您的问题:

您需要处理索引的无效值以消除异常。

private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
 {
        int a, b;

        if (dataGridView1.Rows.Count > 0 && e.RowIndex >= 0 && e.ColumnIndex >= 0)
        {
            try
            {
                a = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[2].Value);
                b = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[4].Value);
                if (b > a)
                {
                    MessageBox.Show("required quantity exceeds stock");
                }
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
                //Or whatever you've planned for...
            }

        }
 }