Solved

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

Posted on 2011-09-03
19
519 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
  • 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
 

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
 

Author Comment

by:tjgrindsted
ID: 36481170
0
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 
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

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

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

The first two articles in this short series — Using a Criteria Form to Filter Records (http://www.experts-exchange.com/A_6069.html) and Building a Custom Filter (http://www.experts-exchange.com/A_6070.html) — discuss in some detail how a form can be…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Basics of query design. Shows you how to construct a simple query by adding tables, perform joins, defining output columns, perform sorting, and apply criteria.

911 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now