Jason
Jason

Reputation: 11615

Setting Image Width/Height in codebehind - ASP.NET, C#

I am trying to set the width and height of images in a datalist in the codebehind.

The plan is to do something more complex than this based on the width/height, so setting width and height in the aspx file to 50% is not an option.

For some reason I always get 0 for width and height. Image1.ImageUrl is what i would expect though. Any ideas? Image is the System.Web.UI.Webcontrols.Image, not a System.Drawing.Image.

    protected void DataList9_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        Image Image1 = (Image)e.Item.FindControl("Image1");

        double height = Image1.Height.Value;
        double width = Image1.Width.Value;
        height = height * 0.5;
        width = width * 0.5;

        Image1.Height = new Unit(height);
        Image1.Width = new Unit(width);
    }

Upvotes: 0

Views: 20334

Answers (4)

Stryder
Stryder

Reputation: 785

I am not sure about c# but I can code it this way in VB.net, so I am sure there is something equivelant and it looks like it will solve your intent if not your actual coding problem.

With dImage
   .Width = 50%
   .Height = 50%
End With

I tried it both with setting the image height in my xaml as well as leaving it out.

--edited for layout purposes.

Upvotes: 1

Kieren Johnstone
Kieren Johnstone

Reputation: 41983

Remember with an img tag, you don't set width and height by default. In this case, unless you set Width and Height, they will be 0 (or undefined). If you need the actual (image, pixels) width and height, you'll need to discover that for yourself by loading the image into memory.

Depending on the filetype, .NET probably has a decoder or the ability to load it already. Load it into a Bitmap then query the width and height there.

Upvotes: 1

DevDave
DevDave

Reputation: 1049

Your code above is referencing a image control that more then likely does not specify a width and or height.

To do what you want I believe you would need to get the source of the image and load it in memory using GDI. Then you could determine the width and height. Then you would be able to do your adjustments to the height and width and apply to the properties of the image tag.

Upvotes: 2

zincorp
zincorp

Reputation: 3282

Have you tried declaring/defining an OnLoad handler for the image and setting the height/width in there?

Upvotes: 0

Related Questions