2

I have an image in a repeater in ASP.NET. I need to set the width of this image dynamically to a value returned from the database. I get the information from the SQL db, then I bind the repeater to the result set or datasource and I try to specify the width of the image in the repeater as follows:

<asp:Image ID="Image1" runat="server" Width='<%# Eval("ImageSize") %>' ImageUrl="~/Images/ProgressBar.jpg"/>

I get an error stating

Specified cast is not valid.

Could this be caused because of the datatype that is being returned from the db?

2
  • What is field datatype and can it be null ? Commented Jun 19, 2012 at 11:44
  • The size cannot be null and the field type returned from DB is Int. Thanks J Commented Jun 19, 2012 at 11:56

2 Answers 2

2

Use System.Web.UI.WebControls.Unit.Parse method:

<asp:Image 
      ID="Image1" 
      runat="server" 
      Width='<%# System.Web.UI.WebControls.Unit.Parse(Eval("ImageSize").ToString()) %>'
      ImageUrl="~/Images/ProgressBar.jpg"/>
Sign up to request clarification or add additional context in comments.

Comments

2

Re-Write in aspx file like this:

Width='<%# ConvertToImageSize(Eval("ImageSize")) %>'

Code-Behind:

protected int ConvertToImageSize(object imageSize)
{
  int i = 0;
  if (imageSize != null)
  {
    i = Convert.ToInt32(imageSize); 

   }

  return i;

}

A bit rough but I hope you can do the rest of handling at your end easily.

2 Comments

Thanks for this. Seems a bit tedious compared to @AVD's solution but still a great answer. Thanks J
I need to set as Percentage not px. how shall i do that?

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.