Reputation: 260
I have one <asp:Image ID="imgBanner1" runat="server"/>
control in my aspx page, then in code behind I have this test code:
Image img = new Image();
img.ImageUrl = "~/img/home/home1.jpg";
//...
imgBanner1 = img; //<--
then when I refresh the page, the src
value of the <img>
is blank and the picture doesn't appear. I tried to put the snippet in Page_Load, Page_Init, Page_PreInit events but still doesn't work. How can I solve this? I need to asign some custom controls of other clases in my pages... thanks for your answers!.
Edit: It works if I do this:
imgBanner1.ImageUrl = img.ImageUrl;
//...
Upvotes: 3
Views: 102
Reputation: 94635
If you want to add a control dynamically into a page then add placeholder (or container - Panel etc) control on it and write following code in page_init/page_load. For more info read MSDN article - How to: Add Controls to an ASP.NET Web Page Programmatically?
Image img = new Image();
img.ImageUrl = "~/img/home/home1.jpg";
PlaceHolder1.Controls.Add(img);
ImageUrl
is a string property and you have to set string image url.
Upvotes: 4
Reputation: 52410
You don't need to instantiate a new Image yourself. This code is generated automatically as a protected field in the page.designer.cs code-behind/beside file. All you need to do is have:
imgBanner1.ImageUrl = "~/img/home/home1.jpg";
in Page_Load
and all will be well.
Upvotes: 3