无法将“System.String”类型的对象强制转换为“System.Web.UI.WebControls.GridViewRow”类型

时间:2016-02-10 08:00:53

标签: asp.net vb.net

我需要你的帮助。我不知道为什么我会收到这个错误。这是我想要做的。我根据数据库中的数据将button填充到GridView中,但我对此没有任何问题。但问题出现在我试图做RowCommand时。我想从每个id获取个人row,以便我可以用于我的sql查询

Protected Sub GridView2_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView2.RowDataBound

    Dim row As GridViewRow = e.Row

    If row.RowType = DataControlRowType.DataRow Then

        Dim lb2 As New LinkButton
        lb2.ID = "lbCancel"
        lb2.Text = "Cancel"
        lb2.CommandName = "CancelRow"
        lb2.CommandArgument = "'<%#Eval('tripID')%>"

        row.Cells(10).Controls.Add(lb2)

        If row.Cells(8).Text = "Driver" Then

            Dim lb As New LinkButton()
            lb.ID = "lbEnd"
            lb.Text = "End"
            lb.CommandName = "EndRow"

            row.Cells(9).Controls.Add(lb)

        End If
    End If

End Sub

Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView2.RowCommand

    If (e.CommandName = "CancelRow") Then
        Dim row As GridViewRow = e.CommandArgument

        Dim index As String = Convert.ToString(DataBinder.Eval(row.DataItem, "tripID"))
    ElseIf (e.CommandName = "EndRow") Then


    End If
    End Sub

我怀疑这个问题是由Dim index As String = Convert.ToString(DataBinder.Eval(row.DataItem, "tripID"))引起的,但是我不知道如何解决它。

希望你们能提供帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

如果您尝试调试代码,您将获得

  

无法将“System.String”类型的对象强制转换为“System.Web.UI.WebControls.GridViewRow”

行错误

Dim row As GridViewRow = e.CommandArgument

您正在尝试将String转换为WebControls GridViewRow。在这种情况下,你应该尝试

Dim row As GridViewRow = DirectCast(DirectCast(e.CommandSource, LinkButton).NamingContainer, GridViewRow)

这会为您提供GridViewRow,并会将您传递的值评估为CommandArgument