views:

806

answers:

3

I get the below error

Unable to cast object of type 'System.String' to type 'System.Data.DataTable'.

This is the code I'm using

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

Thanks

A: 

I'm not a VB guy, but I would have thought you would need to cast the session variable to the correct type (DataTable):

Dim dt As DataTable = CType(Session("Brief"), DataTable);
Mark B
Sorry tried that didn't work.
xtrabits
What error did you get - the same one? Are you sure that that session variable actually contains a DataTable object?
Mark B
@xtrabits, which line throws the exception? This one?: Dim dt As DataTable = Session("Brief")
o.k.w
Get the type of the object by writing this Session("Brief").GetType().ToString(), make sure it is a DataTable.
o.k.w
A: 

I think you need to "cast" Session("Brief") :

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

see example here

RC
A: 

How about this one:

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

Use TryCast and the check of the cast was succesful or not...

And here's version with a bit of LINQ thrown in for good measure:

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
Jakob Gade
Another option to determine if Session("Brief") is a DataTable (instead of using TryCast) would be to use VB's TypeOf operator:If TypeOf Session("Brief") Is DataTable Then ...
Scott Mitchell