ModS
ModS

Reputation: 846

Dynamically set picture src asp.net

is it possible to set the src of a image with a button click. Each of my buttons represents a picture that should be displaying in my "image" area. I need the image Area's SRC property to be affected by the button click. Im using visual studio 2012 with c#.

-Edit : Using AJAX Update panel in visual studio 2012 with C#

Upvotes: 3

Views: 15984

Answers (4)

Elyas
Elyas

Reputation: 121

Inside aspx:

<img id="imagenCabecera" runat="server" />

And inside aspx.vb:

imagenCabecera.Attributes("src") = "url-image.jpg"

Upvotes: 1

Gary Huckabone
Gary Huckabone

Reputation: 412

I noticed if I had not first specified a value for ImageUrl in my .aspx code, I could not then set it in the .aspx.cs code.

Ie, if I had my .aspx code as:

<asp:Image runat="server" id="imgPickLg0101" class="ImgSzLarge" />

I could not set it in the code behind.

However, if I first specified a value for ImageUrl:

<asp:Image runat="server" id="imgPickLg0101" class="ImgSzLarge" ImageUrl="../Images/somepic.jpg" />

Then I could set it in the .aspx.cs code:

imgPickLg0101.ImageUrl = "../Images/DifferentPicture.jpg";

Upvotes: 0

Hardrada
Hardrada

Reputation: 728

Yes. You will be able to accomplish this by using JavaScript and attaching a click handler to the button (onclick="loadImage1()").

loadImage1 function would require you to write the javascript necessary to access the src attribute of the image element and alter it.

You can achieve this with plain javascript (see above concept), or with some javascript library such as jQuery. For cross browser compatibility and to save you from having to write your cross browser safe logic, I would suggest jQuery to handle this.

<img id="img1" src="initialimagehere.jpg"/>

And then you can change the src attribute like this:

$("#img1").attr("src","newimagehere.jpg");

jQuery: this link

Upvotes: 2

loxxy
loxxy

Reputation: 13151

If a postback is acceptable to you for every image change, you may do something like :

In C#:

protected void btnClick(object sender, EventArgs e) {

            Button btn = (Button) sender;    

            switch (btn.ID) {

                case "btn1": img.ImageUrl = "<Image_Url>"; break;

                case "btn2": img.ImageUrl = "<Image_Url>"; break;            
            }
        }

In ASPX Page:

<asp:Image ID="img" runat="server"  />
<asp:Button ID="btn1" runat="server" OnClick="btnClick" />
<asp:Button ID="btn2" runat="server" OnClick="btnClick" />

Upvotes: 2

Related Questions