2

我收到以下错误

无法将“System.String”类型的对象转换为“System.Data.DataTable”类型。

这是我正在使用的代码

Dim str As String = String.Empty

    If (Session("Brief") IsNot Nothing) Then

        Dim dt As DataTable = Session("Brief")
        If (dt.Rows.Count > 0) Then
            For Each dr As DataRow In dt.Rows
                If (str.Length > 0) Then str += ","
                str += dr("talentID").ToString()
            Next
        End If

    End If

    Return str

谢谢

4

3 回答 3

2

我不是 VB 人,但我原以为您需要将会话变量转换为正确的类型(DataTable):

Dim dt As DataTable = CType(Session("Brief"), DataTable);
于 2009-10-04T09:00:52.527 回答
1

这个怎么样:

Dim str As String = ""

If Not Session("Brief") Is Nothing Then
  Dim dt As DataTable = TryCast(Session("Brief"), DataTable)

  If Not dt Is Nothing AndAlso dt.Rows.Count > 0 Then
    For Each dr As DataRow In dt.Rows
      If (str.Length > 0) Then
        str += ","
      End If

      str += dr("talentID").ToString()
    Next
  End If
End If

Return str

使用 TryCast 并检查演员阵容是否成功......

这是一个带有一些 LINQ 的版本,可以很好地衡量:

Dim str As String = ""

If Not Session("Brief") Is Nothing Then
  Dim dt As DataTable = TryCast(Session("Brief"), DataTable)

  If Not dt Is Nothing AndAlso dt.Rows.Count > 0 Then
    str = Join((From r In dt Select CStr(r("talentID"))).ToArray, ",")
  End If
End If

Return str
于 2009-10-04T10:47:23.680 回答
1

我认为您需要“投射” Session("Brief") :

Dim dt As DataTable = CType(Session("Brief"), Datatable)

这里的例子

于 2009-10-04T09:06:06.523 回答