在 asp.net 动态创建多个标签
本文关键字:标签 创建 动态 asp net | 更新日期: 2023-09-27 18:34:57
我想根据用户输入的数字动态创建多个标签。例如,如果用户在文本框中输入 10,则应使用 id label1 - label10 创建 10 个标签,我想在这些标签中放置单独的文本。知道如何使用 c# 尖锐代码 asp.net 做到这一点吗?
类似以下内容的内容应该可以帮助您入门。
// 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
. - 例如,正确的验证,即不允许用户输入数字> 100 或<1。 您可以使用自定义代码或验证控件(如
RangeValidator
和CompareValidator
(进行处理。
读取文本框值并执行循环,在其中创建标签控件的对象并设置 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="server" 属性的窗体。