在asp.net中即时创建多个标签 [英] Create multiple labels on fly in asp.net
本文介绍了在asp.net中即时创建多个标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据用户输入的编号动态创建多个标签.例如,如果用户在文本框中写入10,则应使用ID label1-label10创建10个标签,而我想在这些标签中放置单独的文本.任何想法如何使用c#尖锐代码在asp.net中做到这一点?
I want to create multiple labels on fly based on the number entered by user. For example if user writes 10 in textbox, 10 labels should be created with id label1 - label10 and i want to put separate text in those labels. Any idea how to do it in asp.net with c# sharp code ?
推荐答案
类似以下内容将使您入门.
Something like the following should get you started.
// 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
)进行处理.
- What your actual textbox is, for
MyTextBox
- What text you have in your labels.
- What parent control
MyParentControl
for adding the labels to the page. - What to do when the number is invalid, i.e.,
MyLoggingOutput
. - Proper validation, i.e., don't allow user to enter number > 100 or < 1, for example. You could handle with custom code or with validation controls, such as
RangeValidator
andCompareValidator
.
这篇关于在asp.net中即时创建多个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文