我想根据用户输入的数字在飞行中创建多个标签。例如,如果用户在文本框中写入10,则应使用id label1 - label10创建10个标签,并且我希望在这些标签中放置单独的文本。任何想法如何用asp #c急剧代码在asp.net中做到这一点?
答案 0 :(得分:0)
读取文本框值并执行循环,在其中创建标签控件对象并设置ID和文本属性值
int counter = Convert.ToInt32(txtCounter.Text);
for(int i=1;i<=counter;i++)
{
Label objLabel = new Label();
objLabel.ID="label"+i.ToString();
objLabel.Text="I am number "+i.ToString();
//Control is ready.Now let's add it to the form
form1.Controls.Add(objLabel);
}
假设txtCounter
是TextBox控件,其中用户输入要创建的标签数量,而form1是页面中带有runat =&#34;服务器&#34;属性。
答案 1 :(得分:0)
以下内容应该让您入门。
// get user input count from the textbxo
string countString = MyTextBox.Text;
int count = 0;
// attempt to convert to a number
if (int.TryParse(countString, out count))
{
// you would probably also want to validate the number is
// in some range, like 1 to 100 or something to avoid
// DDOS attack by entering a huge number.
// create as many labels as number user entered
for (int i = 1; i <= count; i++)
{
// setup label and add them to the page hierarchy
Label lbl = new Label();
lbl.ID = "label" + i;
lbl.Text = "The Label Text.";
MyParentControl.Controls.Add(lbl);
}
}
else
{
// if user did not enter valid number, show error message
MyLoggingOutput.Text = "Invalid number: '" + countString + "'.";
}
当然,你需要纠正:
MyTextBox
MyParentControl
。MyLoggingOutput
。RangeValidator
和CompareValidator
。