在运行时将控件从 .cs 文件添加到 asp .net 表单
我有一个网站(使用 asp .net 构建),我想在运行时向其中添加一些文本和图片(我之前不知道数量)。
用户选择参数后,单击一个按钮,该按钮调用以下代码(在 .cs 文件中):
foreach (var car in cars)
{
Label lbl = new Label ();
form1.Controls.Add(lbl);
lbl.Text = car.name;
Image myImage = new Image ();
form1.Controls.Add(myImage);
myImage.ImageUrl = car.imageURL;
}
但是当我运行代码时,我在页面上看不到控件。 我错过了什么吗?
谢谢!
I have a site (build with asp .net) and I want to add to it some text and pictures during runtime (I don't know the amount before).
After the user chooses the parameters, he clicks a button which invokes the following code (in the .cs file):
foreach (var car in cars)
{
Label lbl = new Label ();
form1.Controls.Add(lbl);
lbl.Text = car.name;
Image myImage = new Image ();
form1.Controls.Add(myImage);
myImage.ImageUrl = car.imageURL;
}
but when I run the code, I don't see the controls on the page.
am I missing something?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在设置控件的属性之前,您必须将控件分配给表单。
例如:
更新:
我刚刚创建了一个全新的 Web 应用程序项目,其页面上只有一个按钮;它按预期工作。我建议你做点别的事情。见下文:
以及背后的代码:
You have to assign the control to the form BEFORE setting it's properties.
For example:
UPDATE:
I just created a brand new web application project with a page that only had a button on it; it worked as expected. I suggest you have something else going on. See below:
and the code behind:
尝试在表单中添加占位符控件。然后不要调用 Form1.Controls.Add(....) 使用 PlaceHolder1.Controls.Add(.....)
Try adding a placeholder control onto your form. Then instead of calling Form1.Controls.Add(....) use PlaceHolder1.Controls.Add(.....)
在 Web 窗体上创建动态控件时,必须在 OnInit 或 Page_Load 事件中创建控件并将其添加到控件集合中。
请参考这个问题 以解决您的问题。
When you create dynamic controls on a Web Form, the controls must be created and added to the controls collection either in the OnInit or in the Page_Load events.
Please refer this question in order to solve your issue.
您可以尝试 AndyPeacock 所说的,但查看您的代码,我认为您需要研究的实际上是 Repeaters 和其他数据绑定控件,如 DataListView。
下面是一个如何使用中继器实现此功能的简单示例:
在您的 ASPX 文件中:
在您的 .CS 部分,可能在 Page_Load 中:
看一下 http://www.w3schools.com/ASPNET/aspnet_repeater.asp
You can try what AndyPeacock says but looking at your code I think what you need to research into is actually Repeaters and other databound controls like DataListView.
Here's a quick example of how you could implement this with a Repeater:
In your ASPX file:
And on your .CS part, probably in Page_Load:
Have a look at http://www.w3schools.com/ASPNET/aspnet_repeater.asp
不是答案,但以下精简示例对我有用:
那么您似乎没有发布足够的信息来回答您的问题?
Not an answer, but the following stripped-down sample works for me:
So it seems you have not posted enough information to answer your question?