0

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);
    }

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.