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;
//...
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?
ImageUrlis a string property and you have to set string image url.