我正在编写一个for循环,它显示一个带有chartfx显示的链接列表。chartfx需要一个sqlDataSource。我试图在每次for循环执行一次迭代时提供唯一的ID,但我不能将值或函数传递给它。下面是我的代码中的例子。getSQLID()只是一个返回字符串的函数,我想把它作为我的ID,这都是在aspx页面上完成的,函数在.cs中。任何帮助都将不胜感激,谢谢。
//name of the contentplace holder on the aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server" >
//code behind
Control ctrl = LoadControl("WebUserControl.ascx");
Control placeHolderControl = this.FindControl("Content2");
Control placeHolderControl2 = this.FindControl("ContentPlaceHolder1");
ctrl.ID = "something";
if (placeHolderControl != null)
placeHolderControl.Controls.Add(ctrl);
if (placeHolderControl2 != null)
placeHolderControl2.Controls.Add(ctrl);发布于 2013-03-27 23:53:10
首先,回想一下在设计器中声明的服务器控件是在编译时附加到类的。因此,在运行时尝试在循环中创建多个实例是没有意义的,这就是为什么Id标记中的值必须在编译时知道的原因。
一种替代方法是在后面的代码中创建它们,如下所示:
for (int i=0; i<2; ++i)
{
var chart = new Chart();
chart.Id = "chartId" + i;
chart.DataSourceId = "srcid" + i;
var src = new SqlDataSource();
src.Id = "srcid" + i;
Controls.Add(chart); // either add to the collection or add as a child of a placeholder
Controls.Add(src);
}在您的示例中,将所有这些声明性属性转换为后台代码可能需要一些工作(尽管这是可能的)。另一种方法是创建一个用户控件(ascx),该控件包含现在位于aspx页中的标记。您可以在后台代码中使用以下内容实例化这些控件:
for (int i=0; i<2; ++i)
{
var ctrl = LoadControl("~/path/to/Control.ascx");
ctrl.Id = "something_" + i;
Controls.Add(ctrl); // again, either here or as a child of another control
// make the src, hook them up
}https://stackoverflow.com/questions/15640569
复制相似问题