简体   繁体   中英

Why can't I do this in asp.net webforms?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM