我不明白为什么我不使用任何Integer时为什么会出现System.InvalidCastException?

时间:2019-12-12 04:57:21

标签: sql vb.net datagridview

我正在尝试从DataGridView中获取“购买日期”,并将其与文本框中的字符串进行比较,如果它们相等,则选择了DataGridView中的当前记录。 但是我收到“ $ exception {”从字符串““ Purchase_Date”“转换为'Integer'的类型无效。”} System.InvalidCastException“。我不明白为什么会得到这个即使我没有使用Integer还是异常?

下面是我面临此问题的代码:

        Dim i = 0
        For Each Row As DataGridViewRow In dgPurchases.Rows
            Dim currentdate As String = Format(dgPurchases.Rows("Purchase_Date").ToString(),
            "dd/MM/yyyy")
            If StrComp(currentdate, purchasedate) Then
                dgPurchases.Rows(i).Selected = True
            End If
            i += 1
        Next

1 个答案:

答案 0 :(得分:0)

使用For Each循环并保持计数器是没有意义的。决定要进行For循环还是For Each循环,然后使用正确选择的循环。

如果选择For Each循环,请使用循环控制变量:

For Each row As DataGridViewRow In dgPurchases.Rows
    Dim currentdate As String = Format(row.Cells("Purchase_Date"), "dd/MM/yyyy")

    If StrComp(currentdate, purchasedate) Then
        row.Selected = True
    End If
Next

如果您选择For循环,那么它将提供循环计数器:

For i = 0 To dgPurchases.Rows.Count - 1
    Dim currentdate As String = Format(dgPurchases.Rows(i).Cells("Purchase_Date"), "dd/MM/yyyy")

    If StrComp(currentdate, purchasedate) Then
        dgPurchases.Rows(i).Selected = True
    End If
Next

当您要使用循环计数器的唯一事情是为单个列表编制索引时,For Each循环显然是优越的。

我应该特别提到,按要求解决您的问题的部分是,列名用于索引行的Cells集合,而不是网格的Rows集合。 / p>