0

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

3 回答 3

5

您的问题是您只将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>"));
于 2012-05-01T12:55:53.083 回答
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;
    }
}
于 2012-05-01T13:52:41.870 回答
1

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

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。字符串是不可变的并且有性能损失。

于 2012-05-01T13:10:08.880 回答