2014-12-28 45 views
0

我有一個表單,我試圖用我的數據庫(SQLCe)上的每個項目的控件進行填充。問題是我試圖從數據庫返回的項目之一是圖像。然而,我的原代碼,給了我一個錯誤:循環遍歷每一行,爲每條記錄創建按鈕。無法從數據庫中獲取圖像

Value of type "Byte' cannot be converted to 'System.Drawing.Image' 

這裏是我的原代碼

Private Sub btnCategories_Click(sender As Object, e As EventArgs) Handles btnCategories.Click 

    Dim dt As DataTable = ProducT_CATEGORYTableAdapter.GetData 

    For Each row As DataRow In dt.Rows 

     Dim btn As New btnCategoryTabs() 

     btn.lblCategoryName.Name = DirectCast(row("Category_Name"), String) 
     btn.lblCategoryName.Text = btn.lblCategoryName.Name 
     btn.picPCategoryPicture.Image = DirectCast(row("Image"), Byte) 'Error Here' 

     'Add categories to the Panel 
     flpMainPanel.Controls.Add(btn) 

    Next 

End Sub 

我相信,我必須將圖像轉換,所以我開始用這段代碼亂搞:

Dim Stream As New MemoryStream() 
    Dim image As Byte() = CType('Can't figure out what to put here), Byte()) 
    Stream.Write(image, 0, image.Length) 
    Dim bitmap As New Bitmap(Stream) 

任何幫助將不勝感激。

謝謝。

回答

1

如果您已將圖像數據存儲在您的數據庫中,那麼它將是Byte()即陣列,而不僅僅是一個Byte。然後您必須將該Byte陣列轉換爲Image。你在正確的軌道上。這裏有一個我提前準備好了:

Dim connection As New SqlConnection("connection string here") 
Dim command As New SqlCommand("SELECT Picture FROM MyTable WHERE ID = 1", connection) 

connection.Open() 

Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte()) 

connection.Close() 

Dim picture As Image = Nothing 

'Create a stream in memory containing the bytes that comprise the image.' 
Using stream As New IO.MemoryStream(pictureData) 
    'Read the stream and create an Image object from the data.' 
    picture = Image.FromStream(stream) 
End Using 

http://www.vbforums.com/showthread.php?469562-Saving-Images-in-Databases&highlight=

在你的情況具體而言,就變成了:

'Create a stream in memory containing the bytes that comprise the image.' 
Using stream As New IO.MemoryStream(DirectCast(row("Image"), Byte())) 
    'Read the stream and create an Image object from the data.' 
    btn.picPCategoryPicture.Image = Image.FromStream(stream) 
End Using 
+0

謝謝,這是我需要什麼。 –

相關問題