在asp.net中创建多个标签

时间:2012-05-21 23:23:55

标签: c# asp.net

我想根据用户输入的数字在飞行中创建多个标签。例如,如果用户在文本框中写入10,则应使用id label1 - label10创建10个标签,并且我希望在这些标签中放置单独的文本。任何想法如何用asp #c急剧代码在asp.net中做到这一点?

2 个答案:

答案 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 + "'.";
}

当然,你需要纠正:

  1. MyTextBox
  2. 的实际文本框是什么
  3. 您的标签中包含哪些文字。
  4. 用于向页面添加标签的父控件MyParentControl
  5. 当号码无效时该怎么办,即MyLoggingOutput
  6. 正确验证,即不允许用户输入数字&gt; 100或者&lt;例如,1。您可以使用自定义代码或验证控件来处理,例如RangeValidatorCompareValidator
相关问题