【问题标题】:How to dynamically give customized text/naming conventions to dynamically generated labels/checkboxes?如何动态地为动态生成的标签/复选框提供自定义文本/命名约定?
【发布时间】:2023-04-09 06:07:01
【问题描述】:
我正在尝试通过 for 循环算法为动态生成的复选框命名。提出算法非常简单,但我无法为他们提供名称/复选框文本。我能想到的最好的办法是为生成的所有内容提供一个类似的复选框文本。有没有办法给它们命名?
下面是我想出的代码
int x = ((((DropDownList1.SelectedIndex+1)*(DropDownList1.SelectedIndex+1))-(DropDownList1.SelectedIndex+1))/2)-1;
Label1.Text = x+"";
for (int i = 0; i < x; i++)
{
CheckBox cb = new CheckBox();
cb.Text = "1 & 2";
PlaceHolder1.Controls.Add(cb);
PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));
}
非常感谢任何帮助。
干杯,
贾夫
【问题讨论】:
标签:
c#
asp.net
visual-studio-2008
naming-conventions
dynamically-generated
【解决方案1】:
你可以使用for语句的索引:
int x = ((((DropDownList1.SelectedIndex+1)*(DropDownList1.SelectedIndex+1))-(DropDownList1.SelectedIndex+1))/2)-1;
Label1.Text = x+"";
for (int i = 0; i < x; i++)
{
CheckBox cb = new CheckBox();
cb.Text = String.Format("PrefixName{0}" , Convert.ToString(i+1));
PlaceHolder1.Controls.Add(cb);
PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));
}
【解决方案2】:
您应该使用控件的ID 属性来分配名称。
像这样:
for (int i = 0; i < x; i++)
{
CheckBox cb = new CheckBox();
cb.ID = "checkBox" + i;
PlaceHolder1.Controls.Add(cb);
PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));
}
Text 属性在每个控件中都可以相等。
控件不能有相同的名称 (ID)。