2016-11-14 66 views
0

我有这种形式从SQL表中创建的代码背后:如何使用StringBuilder加入控件?

Dim holder As PlaceHolder = CType(FV.FindControl("plControl"), PlaceHolder) 
    Dim html As New StringBuilder() 

    html.Append("<table>") 

    For Each Row As DataRow In ds.Tables(0).Rows 

    html.Append("<tr style='border: 1px solid black; height:30px;'>") 
    html.Append("<td style='padding-right:40px; width:400px; text-align:right; background-color:lightgray;border: 1px solid black;'><b>") 
    html.Append(Row(columnName:="Name")) 
    html.Append("</b></td>") 
    html.Append("<td style='width:300px; text-align:center; background-color:lightgray;border: 1px solid black;'>") 
    html.Append("</td>") 

    html.Append("<td style='width:300px; text-align:center; background-color:lightgray;border: 1px solid black;'>") 
    html.Append("</td>") 

    html.Append("</tr>") 

    Next 

    html.Append("</table>") 

    holder.Controls.Add(New Literal() With { _ 
        .Text = html.ToString() _ 
       }) 

现在,在这个表我想添加和控制但每次控制在StringBuilder的加入将被识别为一个HTML文本。

我在循环中使用这样的:

Dim btn As New Button 
    btn.Text = "Click me.." 
    AddHandler btn.Click, AddressOf MyButton_Click 
    MyPlaceHolder.Controls.Add(btn) 

但这种控制将在我的桌子的顶部添加。我只想知道有没有什么方法可以在此表中添加Controls?

回答

2

您正在混合添加控件的两种不同方法。对于表格,您正在构建一个HTML字符串,然后将其添加到页面中。对于该按钮,您将创建一个Button对象并在添加该表之前将其添加到页面中。您必须使用一种方法或其他方法(对所有内容使用对象或HTML字符串)。

由于您有按钮的事件处理程序,因此使用Table类构建表可能更容易。

有做的是,这里的一个例子:http://geekswithblogs.net/dotNETvinz/archive/2009/03/17/dynamically-adding-textbox-control-to-aspnet-table.aspx

然后,您可以添加您的按钮到适当的TableCell。

1

您需要使用一个asp.net表,您不能将html混合为一个字符串和Controls。

'create an asp.net table 
Dim table As Table = New Table 

'let's add some cells 
Dim i As Integer = 0 
Do While (i < 5) 

    'create a new control for in the table 
    Dim linkButton As LinkButton = New LinkButton 
    linkButton.ID = ("CellLinkButton_" + i.ToString) 
    linkButton.Text = ("LinkButton " + i.ToString) 

    'create a new table row 
    Dim row As TableRow = New TableRow 

    'create 2 new cells, 1 with text and 1 with the linkbutton control 
    Dim tableCell As TableCell = New TableCell 
    tableCell.Text = ("Cell " + i.ToString) 
    row.Cells.Add(tableCell) 

    tableCell = New TableCell 
    tableCell.Controls.Add(linkButton) 
    row.Cells.Add(tableCell) 

    'add the new row to the table 
    table.Rows.Add(row) 

    i = (i + 1) 
Loop 

'add the table to the placeholder 
PlaceHolder1.Controls.Add(table)