2014-01-21 55 views
0

我有一個數據網格視圖中,在更新按鈕i寫這樣的代碼:無法轉換類型的對象「System.Byte []」中的窗口的應用程序類型「爲System.Drawing.Image」

Dim cid As Integer 
     Dim dtid As Integer 
     Dim cmpname As String 
     Dim dtname As String 
     Dim dtPhone As String 
     Dim dtEmail As String 
     Dim dtimage As Image 


     For i As Integer = 0 To gv.RowCount - 2 
      ' Dim rv = DirectCast(bSource.Current, DataRowView) 
      Dim rv = DirectCast(gv.Rows(i).DataBoundItem, DataRowView) 
      cid = rv.Row.Field(Of Integer)("Cid") 

      dtid = rv.Row.Field(Of Integer)("dtId") 
      cmpname = rv.Row.Field(Of String)("CompanyName") 
      dtname = rv.Row.Field(Of String)("Department") 
      dtPhone = rv.Row.Field(Of String)("Phone") 
      dtEmail = rv.Row.Field(Of String)("Email") 
      dtimage = rv.Row.Field(Of Image)("empimage") 

      adapter.UpdateCommand = New SqlCommand("UPDATE CompanyMaster_tbl SET CompanyName = @CompanyName", con.connect) 
      adapter.UpdateCommand = New SqlCommand("update DepartmentMaster_tbl set dtName = @dtName,dtPhone = @dtPhone,dtEmail = @dtEmail,[email protected] where [email protected]", con.connect) 
      adapter.UpdateCommand.Parameters.AddWithValue("@Cid", cid) 

      adapter.UpdateCommand.Parameters.AddWithValue("@CompanyName", cmpname) 
      adapter.UpdateCommand.Parameters.AddWithValue("@dtId", dtid) 
      adapter.UpdateCommand.Parameters.AddWithValue("@dtName", dtname) 
      adapter.UpdateCommand.Parameters.AddWithValue("@dtPhone", dtPhone) 
      adapter.UpdateCommand.Parameters.AddWithValue("@dtEmail", dtEmail) 
      adapter.UpdateCommand.Parameters.AddWithValue("@dtimage", dtimage) 
      adapter.UpdateCommand.ExecuteNonQuery() 

但我得到這一行中的錯誤 dtimage = rv.Row.Field(Of Image)(「empimage」)無法投射類型爲'System.Byte []'的對象以鍵入'System.Drawing。圖片'

+0

異常包含的回答你的問題,你已經創建圖像類型的變量「dtimage」,應聲明此作爲一個字節數組。 – Ramashankar

回答

4

我不確定語法是否100%正確,所以我會努力工作,我是一個C#程序員交易,但這是你需要做什麼:

Using ms As New MemoryStream(Row.Field(Of Byte())("empimage")) 
    dtimage = New Bitmap(ms) 
End Using 

要保存此相同Bitmap到數據庫中你需要這樣做:

Using ms As New MemoryStream() 
    bmp.Save(ms, ImageFormat.MemoryBmp) 

    Dim bytes(ms.Length) As New Byte() 
    ms.Read(bytes, 0, ms.Length) 

    ' now save that Byte() to the field in the data table 
End Using 

注:MemoryBmp可能不工作 - - 你可能需要使用更具體的東西。這是一個listing of them

+3

語法幾乎就在那裏。在VB.Net數組中使用'()'而不是'[]'。 – JaredPar

+0

@JaredPar:感謝編輯朋友! –

+0

這次我在這裏得到錯誤adapter.UpdateCommand.ExecuteNonQuery()錯誤:沒有從對象類型System.Drawing.Bitmap到已知託管提供程序本機類型的映射。 – user3106114

1

empimage包含字節數組,你需要從它加載圖像:

dtimage = ImageFromBytes(rv.Row.Field(Of Byte())("empimage")) 

... 


Function ImageFromBytes(ByVal bytes As Byte()) As Image 
    Using ms As New MemoryStream(bytes) 
     return Image.FromStream(ms) 
    End Using 
End Function 
+0

這次我在這行中得到錯誤= adapter.UpdateCommand.ExecuteNonQuery()錯誤:沒有從對象類型System.Drawing.Bitmap到已知託管提供程序本機類型的映射 – user3106114

相關問題