C# – How to change an image’s ImageUrl attribute on page load with asp.net and C# in IE

asp.netc++imageinternet-explorer

I have links on a homepage that may or may not have attachments associated with them. If the links have attachments, then an icon will be placed next to the link. The icon will only be there if the link has an attachment.

protected void Page_Load(object sender, EventArgs e)
    {
        foreach (Image pic in imgAttachment)
            {
                 int type = ds.Current_Events[index].AttachmentID;
                 //ds is the dataset

The foreach loop is going through each of the "Current Event" pictures on the homepage then getting the type of attachment associated with each link aka the AtachmentID. The AttachmentID can be a 0, 1, 2, or 3 which means no attachment, photo attached, video attached, or document attached repectively.

A switch statement is then used to change the ImageUrl attribute to the corresponding picture.

                 switch (type)
                     {
                            case 0:
                                break;
                            case 1:
                                pic.ImageUrl = "images/eventicons/Photo.jpg";
                                //changed from just "Photo.jpg"
                                break;
                            case 2:
                                pic.ImageUrl = "images/eventicons/Video.jpg";
                                //changed from just "Video.jpg"
                                break;
                            case 3:
                                pic.ImageUrl = "images/eventicons/Doc.jpg";
                                //changed from just "Doc.jpg"
                                break;
                            default:
                                pic.Visible = false;
                                break;
                      }
                  index++;
            }
    }

The image does not load in IE, however it does work for firefox.

The following is the aspx front

<div>
  <ul>
   <li>
      <asp:HyperLink ID="lblEvent1" runat="server">              
           <img src="images/bar_blank.gif" />
      </asp:HyperLink>
      <asp:Image ID="Image1" runat="server" />
   </li>
   <li>
      <asp:HyperLink ID="lblEvent2" runat="server">
           <img src="images/bar_blank.gif" />
      </asp:HyperLink>
      <asp:Image ID="Image2" runat="server" />
   </li>
  </ul>
</div>

Best Solution

You should add the full path to your images. Instead of

pic.ImageUrl = "Photo.jpg";

you could do this to have ASP.Net write out the path of the photo as well...

pic.ImageUrl = "~/MyImagePath/Photo.jpg";