How do I display an image in a web form in asp.net Visual Studio?

19,381

Solution 1

<asp:Image ID="Image1" runat="server" ImageUrl="~/images/" /> 

This line of code is setting an invalid image url as it only contains the folder path. So in your code you must ensure that you override the Image1's ImageUrl property to valid image file. Based on your requirement here is something you can do.

In aspx page, set the image url to picture1.jpg assuming that option1 is selected by default in the dropdown so picture1.jpg will be displayed on initial page load.

<asp:Image ID="Image1" runat="server" ImageUrl="~/images/picture1.jpg" /> 

Next, set the AutoPostBack property of your dropdown to true so that image source code can be updated dynamically based on dropdown selected value

 <asp:DropDownList 
             ID="DropDownList1"
             runat="server"
             AutoPostBack="true"
             OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList>

In selectedIndexChanged event handler update image source based on the selectedItem

 protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        Image1.ImageUrl = "~/images/" + DropDownList1.SelectedItem.Value;
    }

Hope this helps

Solution 2

<asp:Image ID="Image1" runat="server" ImageUrl="~/images/" />

is setting the url to a directory (folder), not an image. That's why you're getting the small image-box and not an image.

If you want an image to show up when the page loads, set it to a valid image:

<asp:Image ID="Image1" runat="server" ImageUrl="~/images/picture1.jpg" />
Share:
19,381
Dwight Schrute
Author by

Dwight Schrute

Updated on June 04, 2022

Comments

  • Dwight Schrute
    Dwight Schrute almost 2 years

    I have created an image folder in my root project folder

    <asp:Image ID="Image1" runat="server" ImageUrl="~/images/" />
    

    I am linking my images here:

            if (dropDownList.SelectedItem.Value == "Picture 1")
            {
                Image1.ImageUrl = "~/images/picture1.jpg"
            }
    

    When I visit the web page I get a small img box with an x instead of my image.