Solved

can't show image from a DB in a repeater vb.net

Posted on 2011-09-03
19
546 Views
Last Modified: 2012-06-27
Hi
 
I have a problem showing images from a DB, the images are saved like this from another site.
 
cmd.Parameters.Add("@img_type", OleDbType.VarChar).Value = imageType
cmd.Parameters.Add("img_stream", OleDbType.Binary).Value = imageContent
 
So the images is saved to the access db as Binary data. (that work)
 Now i will show the images in a repeater like
 <img src="face.gif" alt="" /> when looking on the serverside code.
 
but if i make the connection and the repeater and make this
 <img src="<%# Container.DataItem("img_stream")%>" alt="" />
 
the code dont show the image, i have some text from the db and it ok, tha code show the text, but not the image.
 Can someone help me, im new to this..
0
Comment
Question by:tjgrindsted
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 9
19 Comments
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36478342
Hi! Src attribure of img is for Url not file content. So to display from database, first you need to implement a httphandler:
http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_27233449.html
0
 

Author Comment

by:tjgrindsted
ID: 36478369
Hi Ivan Vagunin
Thx for the feedback, ok sounds right, my problem is that im not info C-sharp, and i can only finde C-sharp handlers, and when trying to convert em to vb.net its not working, can U or somebody link me to a vb.net handler or maybe show me an ex. on a vb.net image handler !?
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36478498
Look following exmaple: http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.processrequest.aspx.

The code should be like following:

Namespace HandlerExample

    Public Class MyHttpHandler
        Implements IHttpHandler

        ' Override the ProcessRequest method.
        Public Sub ProcessRequest(context As HttpContext) _
        Implements IHttpHandler.ProcessRequest
           
            context.Response.Clear
            context.Response.ContentType = "image/jpeg";
            Dim buffer() As Byte = getImageDataFromDB(context.Request.Url)
            context.Response.OutputStream.Write(buffer, 0, buffer.Length)
            context.Response.End        End Sub

        ' Override the IsReusable property.        
        Public ReadOnly Property IsReusable() As Boolean _
        Implements IHttpHandler.IsReusable

            Get
                Return True
            End Get
        End Property
    End Class

Good cs to vb translaor is http://www.carlosag.net/tools/codetranslator/
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:tjgrindsted
ID: 36480951
have looked at it and im stuck, sry, the ex. is with SQL connection not Access.
If I give u these info, can u then help me !?
I cant get this to work...
<%@ WebHandler Language="VB" Class="ShowImage" %>

Imports System
Imports System.Web
Imports System.Data
Imports System.Data.OleDb
Imports System.IO

Public Class ShowImage 
    Inherits System.Web.UI.Page : Implements IHttpHandler
    
    Dim connStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("App_Data/db1.mdb")

    ' Object created for Oledb Connection
    Dim myAccessConnection As New OleDbConnection(connStr)

    Public Sub openAccessConnection()
        ' If condition that can be used to check the access database connection
        ' whether it is already open or not.
        If myAccessConnection.State = ConnectionState.Closed Then
            myAccessConnection.Open()
        End If
    End Sub

    Public Sub closeAccessConnection()
        ' If condition to check the access database connection state
        ' If it is open then close it.
        If myAccessConnection.State = ConnectionState.Open Then
            myAccessConnection.Close()
        End If
    End Sub
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        If context.Request.QueryString("autoId") Is Nothing Then
            Return
        End If
        Dim connStr As String = ConfigurationManager.ConnectionStrings("ConnStr").ToString()
        Dim autoId As String = context.Request.QueryString("autoId")
        myAccessConnection.Open()
        Using cmd As New OleDbCommand("select * from tblImg where img_id=@autoId", myAccessConnection)
            cmd.Parameters.Add(New OleDbParameter("@autoId", autoId))
            Using reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                reader.Read()
                context.Response.BinaryWrite(DirectCast(reader(reader.GetOrdinal("FileContent")), [Byte]()))
                reader.Close()
            End Using
        End Using
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Open in new window

0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36481060
Hi! So what's the problem with the code? Do you get any error? What is the type img_id? If it is numeric try following:
Using cmd As New OleDbCommand("select * from tblImg where img_id=" + autoId, myAccessConnection)
            Using reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                reader.Read()
                context.Response.BinaryWrite(DirectCast(reader(reader.GetOrdinal("FileContent")), [Byte]()))
                reader.Close()
            End Using
        End Using
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36481062
I meant What is the type of img_id column in DB?
0
 

Author Comment

by:tjgrindsted
ID: 36481165
Its Autonum and Key

when i run the code then i get this error, se the screencasting.
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36481169
Sorry, I don't see any screens
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36481203
I guess you sql request does not return any row, because autoId is considered to be of String type (not numeric). So try this:

Using cmd As New OleDbCommand("select * from tblImg where img_id=@autoId", myAccessConnection)
            Dim paramId As New OleDbParameter("@autoId", OleDbType.Numeric)
            paramId.Value = int.Parse(autoId)
            cmd.Parameters.Add(paramId)
            Using reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                If reader.HasRows Then
                    reader.Read()
                    context.Response.BinaryWrite(DirectCast(reader(reader.GetOrdinal("FileContent")), [Byte]()))
                    reader.Close()
                End If
            End Using
        End Using
0
 

Author Comment

by:tjgrindsted
ID: 36481271
If i use that the VS program is saying that there was build error.
The errors are these http://imageshack.us/photo/my-images/847/error2d.jpg/
If i make a simple site SLET.ASPX
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="SLET.aspx.vb" Inherits="SLET" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Image ID="Image1" runat="server" ImageUrl="showImage.ashx?autoId=1"/> 
    </div>
    </form>
</body>
</html>

Open in new window


i then get a red image cross error on server site and "show code" i get this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
    <form method="post" action="SLET.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE1MTU2MzE5MDhkZIV95aciKHYdJK92JmReSVo+l5lrlifyfkPQg30t5TLX" />
</div>

    <div>
    <img id="Image1" src="showImage.ashx?autoId=1" /> 
    </div>
    </form>
</body>
</html>

Open in new window

0
 
LVL 18

Accepted Solution

by:
ivan_vagunin earned 250 total points
ID: 36482495
I'm sorry, there was a misprint:
Using cmd As New OleDbCommand("select * from tblImg where img_id=@autoId", myAccessConnection)
            Dim paramId As New OleDbParameter("@autoId", OleDbType.Numeric)
            paramId.Value = Int32.Parse(autoId)
            cmd.Parameters.Add(paramId)
            Using reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                If reader.HasRows Then
                    reader.Read()
                    context.Response.BinaryWrite(DirectCast(reader(reader.GetOrdinal("FileContent")), [Byte]()))
                    reader.Close()
                End If
            End Using
        End Using
0
 

Author Comment

by:tjgrindsted
ID: 36491297
hi Ivan

Dont say Sry. im happy that u will help.
I have looked at the code, but i still get a error, its about the fileContent !?
http://imageshack.us/photo/my-images/819/errorjie.jpg/
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36493630
Hi!
The error means that the row is returned, but there is no "FieldContent" column in it. Please check the spelling.
Try to debug: check the number of field returned (reader.FieldCount) and schema (reader.GetSchemaTable) - can you see FileContent field inside schema table?


0
 

Author Comment

by:tjgrindsted
ID: 36498089
0
 
LVL 18

Expert Comment

by:ivan_vagunin
ID: 36498394
Hi! Then you should change
context.Response.BinaryWrite(DirectCast(reader(reader.GetOrdinal("FileContent")), [Byte]()))
to
context.Response.BinaryWrite(DirectCast(reader("img_stream"), [Byte]()))
0
 

Author Comment

by:tjgrindsted
ID: 36505829
Hi u to thx alot, i have learned alot of this thread...thx.
0
 

Author Comment

by:tjgrindsted
ID: 36505840
i mean U ;)
0
 

Author Closing Comment

by:tjgrindsted
ID: 36505845
great help....
0

Featured Post

Veeam gives away 10 full conference passes

Veeam is a VMworld 2017 US & Europe Platinum Sponsor. Enter the raffle to get the full conference pass. Pass includes the admission to all general and breakout sessions, VMware Hands-On Labs, Solutions Exchange, exclusive giveaways and the great VMworld Customer Appreciation Part

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Access developers frequently have requirements to interact with Excel (import from or output to) in their applications.  You might be able to accomplish this with the TransferSpreadsheet and OutputTo methods, but in this series of articles I will di…
Traditionally, the method to display pictures in Access forms and reports is to first download them from URLs to a folder, record the path in a table and then let the form or report pull the pictures from that folder. But why not let Windows retr…
Using Microsoft Access, learn some simple rules for how to construct tables in a relational database. Split up all multi-value fields into single values: Split up fields that belong to other things into separate tables: Make sure that all record…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Suggested Courses

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question