I am displaying an image within each itme of a ListView. I want the image to be centered horizontally as well as vertically in a box. My code is as follows:
Protected Sub MembersLV_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles MembersLV.ItemDataBound
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim LogoImage As System.Web.UI.WebControls.Image = e.Item.FindControl("LogoImage")
Dim LogoLink As HtmlControl = e.Item.FindControl("LogoLink")
Dim di As ListViewDataItem = DirectCast(e.Item, ListViewDataItem)
Dim ImageFileName As String = di.DataItem("FileName")
Dim FilePath As String = String.Format("/Uploads/MembersDirectory/w125h85/{0}", ImageFileName)
If File.Exists(Server.MapPath(FilePath)) Then
LogoImage.ImageUrl = FilePath
Dim BoxHeight As Integer = 101
Dim BoxWidth As Integer = 138
Dim B As New Bitmap(Server.MapPath(FilePath))
Dim BHeight As Integer = B.Height
Dim BWidth As Integer = B.Width
Dim PaddingTop As Integer = Math.Ceiling(BoxHeight - BHeight) / 2
Dim PaddingLeft As Integer = Math.Ceiling(BoxWidth - BWidth) / 2
LogoLink.Attributes.Add("style", String.Format("padding: {0} 0 0 {1};", PaddingTop, PaddingLeft))
End If
End If
End Sub
I simply calculate the amount of padding needed for the top and left of the image for it to be centered, and then add that padding as a style attribute to the surrounding tag.
The code in the aspx file is as follows:
<a href='<%#Eval("Website") %>' id="LogoLink" runat="server">
<asp:Image ID="LogoImage" runat="server" AlternateText='<%#Eval("Name") %>' />
</a>
When I ran this code, no padding had been applied to the <a>
tags. So I did a quick check to ensure that PaddingTop
and PaddingLeft
were being calculted properly using Response.Write
. Strangely, when I ran it this time, the style attribute appeared correctly! But without Response.Write
, there is no style attribute.
What am I doing wrong?