[英]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: 我的aspx页面中有一个
<asp:Image ID="imgBanner1" runat="server"/>
控件,然后在代码后面我有这个测试代码:
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. 然后当我刷新页面时,
<img>
的src
值为空,图片不会出现。 I tried to put the snippet in Page_Load, Page_Init, Page_PreInit events but still doesn't work. 我试图将片段放在Page_Load,Page_Init,Page_PreInit事件中,但仍然无法正常工作。 How can I solve this?
我怎么解决这个问题? I need to asign some custom controls of other clases in my pages... thanks for your answers!.
我需要在我的页面中设置一些其他clases的自定义控件...感谢您的回答!
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. 如果要将控件动态添加到页面中,请在其上添加占位符(或容器 - 面板等)控件,并在page_init / page_load中编写以下代码。 For more info read MSDN article - How to: Add Controls to an ASP.NET Web Page Programmatically?
有关更多信息,请阅读MSDN文章 - 如何:以编程方式将控件添加到ASP.NET网页?
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. ImageUrl
是一个字符串属性,您必须设置字符串图像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.
此代码自动生成为page.hindigner.cs代码隐藏/旁边文件中的受保护字段。 All you need to do is have:
您需要做的就是:
imgBanner1.ImageUrl = "~/img/home/home1.jpg";
in Page_Load
and all will be well. 在
Page_Load
,一切都会很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.