2

我在此代码中收到“无效转换”异常,该异常位于网格的 mousedown 中:

// Get the index of the row and column the mouse is over.
    rowIndexFromMouseDown = grdSale.HitTest(e.X, e.Y).RowIndex;
    colIndexFromMouseDown = grdSale.HitTest(e.X, e.Y).ColumnIndex;
// Drag only if we're not over header, are over count, and there are some tickets
    if ((rowIndexFromMouseDown != -1)
        && (colIndexFromMouseDown == 2)
        && ((int)grdSale.Rows[rowIndexFromMouseDown].Cells["TypeCount"].Value > 0))

从即时窗口:

?rowIndexFromMouseDown
2
?colIndexFromMouseDown
2
?grdSale.Rows[rowIndexFromMouseDown].Cells["TypeCount"].Value
0
?(int)grdSale.Rows[rowIndexFromMouseDown].Cells["TypeCount"].Value
Cannot unbox '(grdSale.Rows[rowIndexFromMouseDown].Cells["TypeCount"]).Value' as a 'int'

网格单元格不显示任何内容,但网格是从 XML 文件填充的,该文件的架构将值定义为值为 0 的整数。正如人们所看到的,这就是单元格的值。那么为什么不能将它拆箱成一个整数以便我可以评估它呢?

4

1 回答 1

3

该值是除 之外的某种类型int,例如doublestring。即使它是隐式可转换类型,例如short,也不能直接拆箱,int除非它的类型是int。您可以使用Convert.ToInt32(value)来转换值。

于 2013-09-20T20:02:35.713 回答