【问题标题】:ASP.Net Error - Unable to cast object of type 'System.String' to type 'System.Data.DataTable'ASP.Net 错误 - 无法将“System.String”类型的对象转换为“System.Data.DataTable”类型
【发布时间】:2009-10-04 08:47:19
【问题描述】:

我收到以下错误

无法将“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

谢谢

【问题讨论】:

  • 顺便说一句...但是我能问一下您为什么要在会话中存储整个数据表吗?您使用的是哪种会话状态?

标签: asp.net vb.net casting asp.net-session


【解决方案1】:

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

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

【讨论】:

  • 你遇到了什么错误——同样的错误?您确定该会话变量实际上包含一个 DataTable 对象吗?
  • @xtrabits,哪一行抛出异常?这个?:Dim dt As DataTable = Session("Brief")
  • 通过写这个Session("Brief").GetType().ToString()获取对象的类型,确保是DataTable。
【解决方案2】:

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

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

参见示例here

【讨论】:

    【解决方案3】:

    这个怎么样:

    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
    

    【讨论】:

    • 确定 Session("Brief") 是否为 DataTable(而不是使用 TryCast)的另一个选项是使用 VB 的 TypeOf 运算符: If TypeOf Session("Brief") Is DataTable Then ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 2021-08-05
    • 2018-02-14
    • 1970-01-01
    相关资源
    最近更新 更多