Winforms N-Tier - Retrieve and display image from sql server database
Am new to N-Tier programming and in the process of learning more, I want to retrieve an image from SQL Server database using N-tier architecture. I have managed to save the image but am facing issues in getting the image from the database, passing it as a parameter and then displaying the image.Data Access Layer Code:
Public Function SelectRecord(ByVal clsdbo_ProductsPara As AppName.BusinessLogic.BLL_Products) As AppName.BusinessLogic.BLL_Products
Dim clsDAL_Products As New AppName.BusinessLogic.BLL_Products
Dim connTemp As SqlConnection = AppName.DataAccess.AppNameDataClass.GetConnection
Dim strSelect As String = "SELECT * FROM [dbo].[Products] WHERE [ProductID] = @ProductID"
Dim cmdSelect As New SqlCommand(strSelect, connTemp)
cmdSelect.CommandType = CommandType.Text
cmdSelect.Parameters.AddWithValue("@ProductID", clsdbo_ProductsPara.ProductID)
Try
connTemp.Open()
Dim rdrTemp As SqlDataReader = strCommandSelect.ExecuteReader(CommandBehavior.SingleRow)
If rdrTemp.Read Then
With clsdbo_ProductsPara
.ProductID = System.Convert.ToString(rdrTemp("ProductID"))
.ProductDesc = If(IsDBNull(rdrTemp("ProductDesc")), Nothing, rdrTemp("ProductDesc"))
.ProductImage = If(IsDBNull(rdrTemp("ProductImage")), Nothing, rdrTemp("ProductImage"))
End With
Else
clsdbo_ProductsPara = Nothing
End If
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
Finally
connTemp.Close()
End Try
Return clsdbo_ProductsPara
End Function
Presentation Layer Code:
Private Sub DisplaySelectedRecordDetails()
Dim clsdbo_ProductsPara As New AppName.BusinessLogic.BLL_Products
clsdbo_ProductsPara.ProductID = System.Convert.ToString(lblProductID.Text)
clsdbo_ProductsPara = clsdbo_ProductsData.SelectRecord(clsdbo_ProductsPara)
If Not clsdbo_ProductsPara Is Nothing Then
Try
txtProductDesc.Text = Convert.ToString(clsdbo_ProductsPara.ProductDesc)
picProductImage.Image = Nothing
If Not IsDBNull(clsdbo_ProductsPara.ProductImage) Then
Dim data As Byte = Convert.ToByte(clsdbo_ProductsPara.ProductImage.GetType)
Dim bw As New BinaryWriter(New MemoryStream)
bw.Write(clsdbo_ProductsPara.ProductImage)
Dim img As Image = Image.FromStream(bw.BaseStream, True)
Me.picProductImage.Image = img
End If
Catch
End Try
End If
End Sub
First, I had like to know what is the correct way of retrieving the image using this method. Secondly I am getting conversion errors Conversion from type 'Byte()' to type 'Byte' is not valid. in the DAL block on the line .ProductImage = If(IsDBNull(rdrTemp("ProductImage")), Nothing, rdrTemp("ProductImage"))
Please help correct the above for me to understand.
Thanks
CL