from worst practice, images and databases

Images should not be stored in database. Also i know this, i tryed to figure out how to display and edit a image in a gridview. The datatype is [image].

The problem is that the sqldatasource control doesnt can handle this type. The pramater only have [object]. Update fails in any case. So i decided to use a objectdatasource control. 2nd part is a typed dataset (xsd).

The gridview edit template contains a upload control. I hooked into the Itemupdateing Event to set the updateparameter with the uplaoded image.

Protected Sub FormView1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewUpdateEventArgs)

Dim myup As FileUpload = CType(FormView1.Row().FindControl("fileupload1"), FileUpload)


Dim ImageStream As IO.Stream = myup.PostedFile.InputStream

Dim lang As Integer = myup.PostedFile.ContentLength

Dim ImageContent(lang) As Byte

ImageStream.Read(ImageContent, 0, lang)

e.NewValues.Item("Bild") = ImageSream


End Try

End Sub

To prevent overwrite of the image in case of empty upload i changed the update command in xsd.

[Bild] =COALESCE(@Bild,bild)

I used a ASHX handler to display the image. As i had already a automatic created "datalayer", i reuse it here.

Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

context.Response.ContentType = "image/jpeg"


context.Response.BufferOutput = False

Dim stream As IO.Stream = Nothing


If Not (context.Request.QueryString("ID")) Is Nothing Then

Dim myDA As New aDSMitarbeiterTableAdapters.MitarbeiterTableAdapter

Dim dt As aDSMitarbeiter.MitarbeiterDataTable = myDA.GetDataBy(context.Request.QueryString("ID"))

Dim bild As Byte() = dt.Rows(0).Item("bild")


End If


End Try

End Sub

At the end it works.


  • images can be transfered with the application ( no directorys, rights...lect)
  • Images are secured angainst direct access


  • slow
  • needs more resources
  • complicated to develop




No Comments