动态创建多个标签并为其分配值

时间:2014-02-05 04:00:32

标签: asp.net vb.net dynamic-controls

我想动态创建多个标签并为其赋值

我创建了多个单选按钮列表并为其指定了值,但是当我对标签使用相同的值时,只显示一个标签控件,标签将循环中的最后一个值作为文本。

我试过的是

Dim table1 As New HtmlTable
For j As Integer = 0 To 2  
    Dim row As New HtmlTableRow()

    Dim cell1 As New HtmlTableCell()
    Dim cell2 As New HtmlTableCell()

    Dim rbl As New RadioButtonList()
    Dim lbl1 As New Label


   For RowIndex As Integer = 0 To 2
        rbl.ID = RowIndex
        rbl.Items.Add(DataSet columnvalues)

        lbl1.ID = Convert.ToInt32(j) ' The problem is in this two line
        lbl1.Text = (DataSet label values)
   Next

    cell1.Controls.Add(rbl)
    cell2.Controls.Add(lbl1)


    row.Cells.Add(cell1)
    row.Cells.Add(cell2)

   table1.Rows.Add(row)

Next
ControlsPlaceHolder.Controls.Add(table1)

2 个答案:

答案 0 :(得分:1)

将循环更改为

   For RowIndex As Integer = 0 To 2
        rbl.ID = RowIndex
        rbl.Items.Add(DataSet columnvalues)
        Dim lbl1 As New Label
        lbl1.ID = Convert.ToInt32(j) ' The problem is in this two line
        lbl1.Text = (DataSet label values)
        cell2.Controls.Add(lbl1)
        cell2.Controls.Add(new LiteralControl("<br />"))
   Next

否则,您只创建一个带有最后一个值的标签。

区别在于您只有一个RadioButtonList并且您正在添加N个项目。但在这种情况下你必须创建N个标签。

答案 1 :(得分:0)

您需要使用RadioButton列表项创建标签,因此使用 RowIndex 标签ID不是 J

试试这个

 Dim table1 As New HtmlTable
        For j As Integer = 0 To 2
            Dim row As New HtmlTableRow()
            Dim cell1 As New HtmlTableCell()
            Dim cell2 As New HtmlTableCell()
            Dim rbl As New RadioButtonList()
            For RowIndex As Integer = 0 To 2
                rbl.ID = RowIndex
                rbl.Items.Add("Hi")
                Dim lbl1 As New Label()
                lbl1.ID = "Hi" + RowIndex.ToString
                lbl1.Text = "hello"
                lbl1.Height = "25"
                cell2.Controls.Add(lbl1)

               ' Add This
                cell2.Controls.Add(new LiteralControl("<br />"))
            Next
            cell1.Controls.Add(rbl)
            row.Cells.Add(cell1)
            row.Cells.Add(cell2)
            table1.Rows.Add(row)
        Next
        PlaceHolder1.Controls.Add(table1)

此行将为您提供控件之间的换行符

PlaceHolder1.Controls.Add(new LiteralControl("<br />"))