从代码后面添加asp:Button

时间:2012-05-01 12:49:33

标签: c# asp.net

我正在构建一个代码隐藏。该表是数据库记录的列表(每行一个记录),我需要为每一行添加一个删除按钮。要做到这一点,我当然需要构建一个具有唯一ID的按钮。为此,我想出了以下内容......但这不起作用。有关如何使其工作的任何提示?

Button deleteButton = new Button();
deleteButton.ID = "deleteStudentWithID" + singleStudent.ID.ToString();
deleteButton.Text = "X";

string row = "<tr>";
row += "<td class=\"style5\">"+deleteButton.ClientID +"</td>";
row += "</tr>";

3 个答案:

答案 0 :(得分:4)

您的问题是,您只是将控件的ClientID添加到html中,而不是将控件添加到页面本身。

Controls.Add(new LiteralControl("<table>"));

foreach(var singleStudent in students)
{
    Controls.Add(new LiteralControl("<tr>"));

    //Code to add other columns

    Button deleteButton = new Button();
    deleteButton.ID = "deleteStudentWithID" + singleStudent.ID.ToString();
    deleteButton.Text = "X";

    Controls.Add(new LiteralControl("<td class=\"style5\">"));
    Controls.Add(deleteButton);
    Controls.Add(new LiteralControl("</td></tr>");
}

Controls.Add(new LiteralControl("</table>"));

答案 1 :(得分:3)

不要在后面的代码中创建整个表标记,而是使用ASP.NET提供的控件。

例如,将其放在.aspx:

<table>
    <asp:Repeater runat="server" ID="MyRepeater1">
        <ItemTemplate>
            <tr>
                <td><%# Eval("StudentName")%></td>
                <td>... other student object bindings ...</td>
                <td>
                    <asp:Button runat="server" ID="MyDeleteButton"
                            CommandArgument='<%# Eval("ID")%>'
                            CommandName="Delete"
                            OnCommand="MyDeleteButton_Command"
                            Text="X" />
                </td>
            </tr>
        </ItemTemplate>
    </asp:Repeater>
</table>

并将其包含在您的代码隐藏中:

protected void Page_Load(object sender, EventArgs e)
{
    MyRepeater1.DataSource = new MyStudent[]
        {
            new MyStudent()
                {
                    ID = 1,
                    StudentName = "Student 1"
                },
            new MyStudent()
                {
                    ID = 2,
                    StudentName = "Student 2"
                }
        };
    MyRepeater1.DataBind();
}

protected void MyDeleteButton_Command(object sender, CommandEventArgs e)
{
    switch (e.CommandName)
    {
        case "Delete":
            // stuff for deleting by e.CommandArgument
            break;
    }
}

答案 2 :(得分:0)

我能想到的问题的最佳解决方案是

Button deleteButton = new Button();
deleteButton.ID = "deleteStudentWithID" + singleStudent.ID.ToString();
deleteButton.Text = "X";

StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
deletedButton.RenderControl(htmlWriter);

string row = "<tr>";
row += "<td class=\"style5\">"+sb.toString(); +"</td>";
row += "</tr>";

这样你就可以得到任何控件的HTML。 :)如果你从后面的代码动态构建HTML,那么尽量不要使用字符串而不是StringBuilder。字符串是不可变的并且具有性能损失。