Loop through datagrid to display images

webwiz082
04-10-2007, 08:35 PM
Hi all:

Let's say I have a datagrid on my website. The values to this datagrid are below:

AttachmentID
697
698
699
700

Each of those 3-digit numbers represents an AttachmentID (which ultimately represents an image). What I want to do is create an image tag for each one of those, but I have no idea how to loop through a datagrid. I have an "attachmentHandler" page which actually retreives the image for each AttachmentID. So if I had this code:

<asp:Image ID="image11" runat="server" ImageUrl="~/Handlers/AttachmentHandler.ashx?AttachmentID=697"></asp:Image>
<asp:Image ID="image12" runat="server" ImageUrl="~/Handlers/AttachmentHandler.ashx?AttachmentID=698"></asp:Image>

I would get two of the correct images. The code on my website is below:

Dim MySQL2 As SQLCommand
MySQL2 = New SqlCommand("SELECT AttachmentID from Attachments where ArticleID=" & Article, DBConnection)
Dim dt as New DataTable()
Dim dcName as New DataColumn("AttachmentID", GetType(Integer))
dt.Columns.Add(dcName)
Dim DataAdapter As New SqlDataAdapter

MySQL2.ExecuteNonQuery()

DataAdapter.SelectCommand = MySQL2
DataAdapter.Fill(dt)

dgPeople.DataSource = dt
dgPeople.DataBind()

So all I wanna do is loop through the datagrid, and for each row in the datagrid, place an image tag in a string which captures the Attachment ID at the very end of it. Something like this:

Dim Image as String
Dim row As DataGridItem
For Each row In dgPeople.Items
Image = "<img src="~/Handlers/AttachmentHandler.ashx?AttachmentID= " & AttachmentID & >"
Next

Then I have to find out a way to actually use the Image string to display the images.

Any help would be appreciated.
Thanks,
-Wes

wayneph
04-11-2007, 06:56 AM
AHHHH!!!!!! Don't loop through a dataset. That is the Classic ASP way of doing things. You can do this very easially using normal databinding.

Create a DataGrid and add a Template column. In the Template column add an Image control with runat="server" and an ID. Then in the ImageURL field you can use a binding Expression similar to the one below to get the concatenated URL. (If you're using .NET 2.0, The GridView control actually contains an ImageField Column Type that makes this even easier.)
<asp:TemplateColumn HeaderText="Image Column">
<ItemTemplate>
<asp:Image runat="server" Id="myImage"
ImageUrl='<%# String.Format("~/Handlers/AttachmentHandler.ashx?AttachmentID={0}", _
DataBinder.Eval(Container, "DataItem.AttachmentID")) %>' />
</ItemTemplate>
</asp:TemplateColumn>I haven't actually tested this, so the Line Breaks may be a little off, but I think it should work.

webwiz082
04-11-2007, 07:47 AM
Thanks for the reply, wayneph... but that code didn't work. It just came up as a borken image.

I'll keep on tryin' different things though.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum