Nishant Kumar
Nishant Kumar

Reputation: 6083

how to change html image src by c#

<img src ="~/UserControls/Vote/Images/Arrow Up.png" id = "vote-up-off" 
        runat = "server" alt ="vote up" 
class="voteupImage" style="height: 45px; width: 44px"/>

here i want to change src of image for certain condition like

if ( a==4)
{
src  url  shuld be ......
}
else
{ 
src  url should be...
}

Upvotes: 4

Views: 35651

Answers (5)

Syed Mohamed
Syed Mohamed

Reputation: 1379

Try this, its working for me

<img src="_images/<%= AssignImageURL() %>" alt="Logo" />

C# Method

protected string AssignImageURL()
{
    String ID = Convert.ToString(Session["id"]);
    ds = sq.SelectQuery("Select LogoURl from table where ID='"+ ID+"' ");
    if (Convert.ToString(ds.Tables[0].Rows[0][0]).Trim() != "")
        return Convert.ToString(ds.Tables[0].Rows[0][0]).Trim();
    else
        return "Logo.jpg";
}

Upvotes: 0

PaRsH
PaRsH

Reputation: 1320

if (someCondition)
{
    vote-up-off.Attributes["src"] = ResolveUrl("~/UserControls/pic.png");
}

Upvotes: -2

KhanZeeshan
KhanZeeshan

Reputation: 1410

HTML

<img src="~/UserControls/Vote/Images/Arrow Up.png" 
         id="VoteUpOff" 
         runat="server" alt ="vote up" 
         class="voteupImage" 
         style="height: 45px; width: 44px"
    />

Server-Side

if (someCondition)
{
    VoteUpOff.Attributes["src"] = ResolveUrl("~/UserControls/foo.png");
}

Keep In mind to see the changes you have to place the "img" in UpdatePanel After doing the changes Update the UpdatePanel if its UpdateMode=Conditional otherwise it'll update automatically if its Property ChildAsTriggers=True

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

First you need to give an id name which can be used as variable:

<img src="~/UserControls/Vote/Images/Arrow Up.png" 
     id="VoteUpOff" 
     runat="server" alt ="vote up" 
     class="voteupImage" 
     style="height: 45px; width: 44px"
/>

And in your code behind you could use this variable:

if (someCondition)
{
    VoteUpOff.Attributes["src"] = ResolveUrl("~/UserControls/foo.png");
}

Upvotes: 5

Jarrett Widman
Jarrett Widman

Reputation: 6429

You'll want to change the id to something without hyphens, but then it would be

voteUpOff.Attributes["src"] = "myImage.png";

Upvotes: 2

Related Questions