How to Display an Image Using an Image Control in Visual Basic.NET
If you have not done so already, create a new web site. To do so, open Visual Studio and click File > New > Web Site. Using ‘Visual Basic’ as the template, select ASP.NET Empty Web Site, name the file ImageControl-VB and click OK. Also, make sure to download the source code as it will contain the image that will be used in this tutorial.
Right click the web site name and click Add New Item. Using ‘Visual Basic’ as the template, select Web Form, leave the file name as Default.aspx, and click add. Default.aspx will be created and you will see it in source view. Place two Button controls inside the div tags and place an Image control below the second Button control.
<asp:Button ID="Button1" runat="server" Text="Show Image" />
<asp:Button ID="Button2" runat="server" Text="Remove Image" />
<asp:Image ID="Image1" runat="server" />
Switch to design view of Default.aspx and double click the “Show Image” button to create an event handler event in the code behind page. In this event, we will set the visibility of Image1 to true, which will reveal the image on the web form. Now switch back to design view and double click the “Remove Image” button to create an event handler. We will do the opposite and set the visibility of Image1 to false, which will remove the appearance of the image on the web page.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Image1.Visible = True
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Image1.Visible = False
Right click the web site name and click Add New Folder. Name the folder Images, as this will hold the image to be used on the web site. Now right click the folder and click Add Existing Item. Browse to the directory that you saved the source file and add the image “v4 octagon 1.png”. Expand the Images folder and you should now see the “v4 octagon 1.png” image in the folder.
Now click the Image control that we placed in the source view and look in the Properties window. Next to the ‘ImageUrl’ row, click the browse button and a “Select Image” window will appear. Click the Images folder, click the “v4 octagon 1.png” image and click OK. Now next to the ‘Visible’ row, change the property to “False”.
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/v4 octagon 1.png" Visible="False" />
Run the web site and you will see two buttons, “Show Image” and “Remove Image”. Click the “Show Image” button and the image we used for the ImageUrl will appear:
When the “Remove Image” button is clicked, the image will disappear from the page.
Thanks for reading and make sure to download the source files to get a better understanding of how the code works.