从代码隐藏中添加 asp:Button

本文关键字:asp Button 添加 代码 隐藏 | 更新日期: 2023-09-27 18:32:59

我正在构建一个代码隐藏。该表是数据库记录的列表(每行一条记录),我需要为每行添加一个删除按钮。为此,我当然需要为此构建一个具有唯一 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>";

从代码隐藏中添加 asp:Button

您的问题是您只将控件的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>"));

不要在代码隐藏中创建整个表标记,而是使用 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;
    }
}

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

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。字符串是不可变的,并且会降低性能。