Datagridview c# 中指定的转换不是有效错误

Specified cast is not valid error in Datagridview c#

这是一个我以前从未遇到过的非常奇怪的错误。我在我的数据网格视图中添加了一个复选框,如下所示:

DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
datagrid.Columns.Insert(0, checkBoxColumn);

我收到错误

Specified cast is not valid

它在数据网格的单元格格式中突出显示了这一点:

for (int i = 0; i <= this.datagrid.Rows.Count - 1; i++)
{
    if ((int)datagrid.Rows[e.RowIndex].Cells[7].Value <= 5)
    {
        this.datagrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
    }

这将检查单元格 7 中的值是否低于该值或等于 5,以及是否将其更改为红色。我曾尝试将单元格更改为 8,因为我认为自从我在 0 处添加了一个新列以来它已经移动了,但它没有用。

试试这个

for (int i = 0; i <= this.datagrid.Rows.Count - 1; i++)
{
    if (Convert.ToInt32(datagrid.Rows[e.RowIndex].Cells[7].Value) <= 5)
    {

    }

尝试使用 int.TryParse,只有当单元格的值可以成功解析为 int 时,它才会解析单元格的值。像这样:

int temp;

for (int i = 0; i <= this.datagrid.Rows.Count - 1; i++)
{        
    if (int.TryParse(datagrid.Rows[e.RowIndex].Cells[7].Value.ToString(), out temp) == true) 
    {
         if (temp <= 5)
         {
             this.datagrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
         }
    }

至少这将停止抛出异常,您可以确定您的单元格格式是否正常工作。我猜你的数据集中有一行在第 7 列中有错误值或空值 and/or 8。如果你在位置零添加了这个新的复选框列,那么你现在需要引用 .Cells[8].

引用列的更好方法是通过它们的名称。然后,如果您将来添加或删除列,则不会在整个代码中弄乱其余的列索引引用。如果上述方法有效,请尝试此操作:

if (int.TryParse(datagrid.Rows[e.RowIndex].Cells["yourColumnName"].Value, out temp) == true) 

要使用此方法,您必须在创建和添加列时指定 .Name 列。