我如何测试DataGridViewCell的类型?

时间:2011-09-19 21:33:01

标签: .net c#-4.0

我试着测试myDataGridViewCell是否是DataGridViewCheckBoxCell

if(myDataGridViewCell.ValueType is DataGridViewCheckBoxCell) ...

但这会发出警告:

  

给定的表达式永远不会提供'System.Windows.Forms.DataGridViewCheckBoxCell')类型

如何测试DataGridViewCell的类型?

2 个答案:

答案 0 :(得分:2)

if (myDataGridViewCell is DataGridViewCheckBoxCell)

您的代码正在检查ValueType property的值是否可转换为DataGridViewCheckBoxCell 由于ValueType始终包含System.Type实例,因此它永远不会是DataGridViewCheckBoxCell,因此编译器会向您发出警告。

答案 1 :(得分:2)

ValueType是单元格所拥有的数据值的类型。那不是你想要的。

要测试它的细胞类型,请执行以下操作:

if (myDataGridViewCell is DataGridViewCheckBoxCell)
 ...

(对于DataGridViewCheckBoxCell和所有子类型都是如此)

if (myDataGridViewCheckBoxCell != null &&
    myDataGridViewCheckBoxCell.GetType() == typeof(DataGridViewCheckBoxCell))
    ...

(仅适用于DataGridViewCheckBoxCell)。