C# 如何为动态生成的标签/复选框动态赋予自定义文本/命名约定?
我试图通过一个for-a算法的循环为动态生成的复选框命名。提出的算法非常简单,但我无法给他们命名/复选框文本。我能想到的最好的方法就是为生成的所有内容创建一个类似的复选框文本。有办法给他们命名吗 下面是我想出的代码C# 如何为动态生成的标签/复选框动态赋予自定义文本/命名约定?,c#,asp.net,visual-studio-2008,naming-conventions,dynamically-generated,C#,Asp.net,Visual Studio 2008,Naming Conventions,Dynamically Generated,我试图通过一个for-a算法的循环为动态生成的复选框命名。提出的算法非常简单,但我无法给他们命名/复选框文本。我能想到的最好的方法就是为生成的所有内容创建一个类似的复选框文本。有办法给他们命名吗 下面是我想出的代码 int x = ((((DropDownList1.SelectedIndex+1)*(DropDownList1.SelectedIndex+1))-(DropDownList1.SelectedIndex+1))/2)-1; Label1.Text = x+"";
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/>"));
}
int x=(((DropDownList1.SelectedIndex+1)*(DropDownList1.SelectedIndex+1))-(DropDownList1.SelectedIndex+1))/2)-1;
标签1.Text=x+“”;
对于(int i=0;i ”);
}
非常感谢您的帮助
干杯,
Jaf您应该使用控件的
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/>"));
}
for(int i=0;i ”);
}
Text
属性在每个控件中可以相等。控件不能有相同的名称(ID)。可以使用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/>"));
}
int x=(((DropDownList1.SelectedIndex+1)*(DropDownList1.SelectedIndex+1))-(DropDownList1.SelectedIndex+1))/2)-1;
标签1.Text=x+“”;
对于(int i=0;i ”);
}