0

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?

2
  • That's what shows up when I view the source. Commented Aug 4, 2016 at 14:29
  • Is the event registered? In your OnLoad method or something close to it, you need to subscribe to the event, otherwise the publisher is oblivious. Not sure about everything in your code, but using what is available right now, Content.OnClick += btnEdit_OnClick or something similar to that. Commented Aug 4, 2016 at 14:30

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.