asp.net - How to change an Image url programmatically

Set or change Image ImageUrl programmatically
Image is an asp.net web server control that allow us to display an image on a web page. Image server control let us works with images from server side code. we can display any valid image in a web page that is supported by requesting web browser.

we can specify the image url in Image control by its ImageUrl property. we also can align the image and set an alternate text for the specified image by using Image control's built in properties. we also can set image's border color, border width and border style programmatically at run time.

Image control's ImageUrl property allow us to set or change an image control's image url (image source) programmatically at run time. so ImageUrl property help us to display a new image instead an old image. it allow us to switch different images in one place.

the following asp.net c# example code demonstrate us how can we change image source programmatically at run time using its ImageUrl property.
ImageImageUrl.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Image1.ImageUrl = "~/Images/Fish4.jpg";

    }
    protected void Button2_Click(object sender, System.EventArgs e)
    {
        Image1.ImageUrl = "~/Images/Fish5.jpg";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to set, change Image ImageUrl programmatically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy; font-style:italic;">Image Example: Change ImageUrl</h2>
        <asp:Image 
             ID="Image1" 
             runat="server"
             BorderColor="SandyBrown"
             BorderWidth="2"
             ImageUrl="~/Images/Fish3.jpg"
             />
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server"
             ForeColor="RosyBrown"
             Text="Change: ImageUrl Fish4"
             Height="45"
             OnClick="Button1_Click"
             Font-Bold="true"
             />
        <asp:Button 
             ID="Button2" 
             runat="server"
             ForeColor="RosyBrown"
             Text="Change: ImageUrl Fish5"
             Height="45"
             OnClick="Button2_Click"
             Font-Bold="true"
             />
    </div>
    </form>
</body>
</html>
Related asp.net examples