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

时间:2013-03-26 15:11:06

标签: c# asp.net html sqldatasource chartfx

我正在写一个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);

1 个答案:

答案 0 :(得分:0)

首先,回想一下,设计器中声明的服务器控件在编译时附加到您的类。因此,尝试在运行时在循环中创建多个实例是没有意义的,这就是为什么在例如运算符中的值。必须在编译时知道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);
}

在你的情况下,将所有这些声明性属性转换为后面的代码可能有点工作(虽然它是可能的)。另一种方法是创建一个包含现在在aspx页面中的标记的用户控件(ascx)。您可以使用以下内容实例化代码中的控件:

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
}