Johnny Bones
Johnny Bones

Reputation: 8402

Rendering a button in C# code-behind

I'm trying to build a table in code-behind. What I have looks like this:

Content += "<tr>";
Content += "<td>" + dt.Rows[i]["Provision"].ToString() + "</td>";
Content += "<td>" + dt.Rows[i]["MarkForReview"].ToString() + "</td>";
Content += "<td>" + dt.Rows[i]["IssueType"].ToString() + "</td>";
Content += "<td>" + dt.Rows[i]["Resolution"].ToString() + "</td>";
Content += "<td>" + dt.Rows[i]["Feedback"].ToString() + "</td>";
Content += "<td><input type=\"button\" ID=\"btnEdit\" runat=\"server\" OnClick=\"btnEdit_OnClick\" Text=\"Edit\" /></td>";
Content += "</tr>"; 

The problem is in how I'm rendering the Edit button. When the code runs, what's rendered for the button looks like this:

<td><input type="button" ID="btnEdit" runat="server" OnClick="btnEdit_OnClick" Text="Edit" /></td>

it keeps giving me a "JavaScript runtime error" that btnEdit_OnClick doesn't exist, but I have this in my code-behind:

    protected void btnEdit_OnClick(object sender, EventArgs e)
    {
        MdlCommentsExtender.Enabled = true;
        MdlCommentsExtender.Show();
        ScriptManager.GetCurrent(this).SetFocus(this.txtCommentBox);
    }

Also, the button renders with no text. It's just a small gray button.

Any ideas what I'm doing wrong?

Upvotes: 0

Views: 761

Answers (1)

Win
Win

Reputation: 62260

You can render a button as a literal. However, no event will be attached to it, because it is not in the control tree.

In other words, the click event will not be trigger when the button posts back to server.

Here is an example -

protected void Page_Init(object sender, EventArgs e)
{
    var btnEdit = new Button {ID = "btnEdit", Text = "Edit" };
    btnEdit.Click += btnEdit_OnClick;
    PlaceHolder1.Controls.Add(btnEdit);
}

ASPX

<%@ Page Language="C#" ... %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <form id="form1" runat="server">
        <asp:PlaceHolder runat="server" ID="PlaceHolder1" />
    </form>
</body>

Upvotes: 2

Related Questions