ASP.Net error. Cannot cast object of type "System.String" to type "System.Data.DataTable"
I am getting the following error
Cannot cast object of type 'System.String' to type 'System.Data.DataTable'.
This is the code I am 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
thank
+2
source to share
3 answers
How about this:
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 execution check was successful or not ...
And here's a 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
+1
source to share