首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用变量或函数在HTML语言中声明我的SqlDataSource ID

如何使用变量或函数在HTML语言中声明我的SqlDataSource ID
EN

Stack Overflow用户
提问于 2013-03-26 23:11:06
回答 1查看 272关注 0票数 0

我正在编写一个for循环,它显示一个带有chartfx显示的链接列表。chartfx需要一个sqlDataSource。我试图在每次for循环执行一次迭代时提供唯一的ID,但我不能将值或函数传递给它。下面是我的代码中的例子。getSQLID()只是一个返回字符串的函数,我想把它作为我的ID,这都是在aspx页面上完成的,函数在.cs中。任何帮助都将不胜感激,谢谢。

代码语言:javascript
复制
     //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);
EN

回答 1

Stack Overflow用户

发布于 2013-03-27 23:53:10

首先,回想一下在设计器中声明的服务器控件是在编译时附加到类的。因此,在运行时尝试在循环中创建多个实例是没有意义的,这就是为什么Id标记中的值必须在编译时知道的原因。

一种替代方法是在后面的代码中创建它们,如下所示:

代码语言:javascript
复制
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页中的标记。您可以在后台代码中使用以下内容实例化这些控件:

代码语言:javascript
复制
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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15640569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档