2009-10-04 81 views
2

我得到下面的錯誤ASP.Net錯誤 - 無法轉換類型「System.String」的對象鍵入「System.Data.DataTable」

無法轉換類型「System.String」的對象鍵入'System.Data.DataTable'。

這是我使用

代碼

昏暗str作爲字符串=的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 

感謝

+0

它的旁邊......但我可以問你爲什麼要在會話中存儲整個數據表,以及你使用了什麼樣的會話狀態? – JonAlb 2011-11-09 14:43:02

回答

2

我不是一個VB的傢伙,但我還以爲你需要將會話變量轉換爲正確的類型(DataTable):

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

對不起,沒有奏效。 – xtrabits 2009-10-04 09:45:37

+0

你得到了什麼錯誤 - 同一個?你確定該會話變量實際上包含一個DataTable對象嗎? – 2009-10-04 09:50:08

+0

@xtrabits,哪行引發異常?這個?:Dim dt As DataTable = Session(「Brief」) – 2009-10-04 09:51:37

1

我認爲你需要t ○ 「投」 會議( 「簡報」):

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

見例如here

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 
+0

如果Session(「Brief」)是一個DataTable(而不是使用TryCast),另一個選擇是使用VB的TypeOf運算符: 如果TypeOf Session(「Brief」)是DataTable那麼...... – 2010-08-31 21:51:58

相關問題