Search code examples
asp.netdatalistdataboundasp.net-controlsdatalistitem

Set image control image dynamically from server side asp.NET


I have a webforms site where users upload files, the file name etc is saved to DB. These files are then displayed in a datalist. I'm trying to get this datalist to show different images (icons) to represent the file types.

This is my code behind. fm.getIcon is a custom function that returns the full file path on the server to the approppriate image which represents the file type.

When i debug the code i can verify that the image does exist at the imgFile path

Private Sub DataList1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList1.ItemDataBound

        Dim docName As Label = e.Item.FindControl("fileNameLabel")
        Dim docImage As Image = e.Item.FindControl("image1")
        Dim imgFile As String = fm.getIcon(My.Computer.FileSystem.GetFileInfo(docName.Text).Extension)
        docImage.ImageUrl = imgFile

End Sub

My problem is that the image is not loading. If i replace imgFile with a hardcoded path to an image it works fine.

What am i missing ?


Solution

  • Please try this.

    // 1st Method

    string fileLocation = Server.MapPath("~/Images/MyFile.jpg");
    
    FileInfo fileInfo = new FileInfo(fileLocation);
    
    string fileExtension = fileInfo.Extension;
    

    // 2nd Method

    System.IO.Path.GetExtension(Server.MapPath("~/Images/MyFile.jpg")); // Result: .jpg
    

    // Your get icon method

    docImage.ImageUrl = "~/Icons/" + 
    fm.getIcon(Path.GetExtension(Server.MapPath("~/Images/MyFile.jpg")));
    
    public string getIcon(string extension)
    {
      switch (extension.ToLower())
      {
        case ".asa":
          return "asa.png";
        case ".asax":
          return "asax.png";
        case ".ascx":
          return "ascx.png";                
        default:
          return "unknown.png";
      }
    }