I am building a page from the code behind. I add a button and set its attributes like this:
var Button1 = new Button();
Button1.Text = "Purge Course Comments";
Button1.Attributes.Add("OnClientClick", "javascript: Purge();");
pageButtons.Controls.Add(Button1);
The button is being added to a div called "pageButtons". When I test the program, the button appears on the screen normally, but when I click it, nothing happens other than the browser posting back.
This page must be built from the code behind, so I can't add the button directly to the page, like this (which would work):
<asp:Button ID="Button1" runat="server" Text="Close Window" OnClientClick="Purge;"/>
Basically, I need to be able to call the function from the code behind, but I'm not having much luck. Can someone tell me what I'm doing wrong?
EDIT: I've looked at the similar questions on Stackoverflow, but I can't find a single one that has an answer that works for me in this situation.
EDIT: For clarity, here's the purge function that I've defined on the page:
function PurgeCourse() {
strCourseId = getQueryString("Id");
if (strCourseId == "") {
strCourseId = getQueryString("CourseId");
}
window.open("Purge.aspx?id=" + strCourseId);
parent.window.close();
}
If I just add the button manually to the page, as in the example above, it works. However, I can't seem to call it from the code behind.
EDIT: I tried a suggestion from below and now my code looks like this:
var Button1 = new Button();
Button1.Text = "Purge Course Comments";
Button1.OnClientClick = "javascript: Purge();";
pageButtons.Controls.Add(Button1);
Unfortunately, this didn't work either. I will reiterate, though, that the function does work if I manually add the button to the page and set the OnClientClick attribute to call Purge(). It just seems that I can't get to the function from the code behind, which is frustrating because I can't see why. This is a small test page with only a function and a div and the code behind. I can't see where the problem is.
EDIT: I just tried another thing, just to see if it would work. I did the following:
Button1.OnClientClick = "javascript: parent.window.close();";
And this worked, so the button can at least use inline javascript code. It's just not "seeing" my function that's on the page from the code behind.
Purgefunction somewhere else and have included it in the page? Also, I'm fairly sure you should add it likeButton1.Attributes.Add("onclick", "javascript:Purge();");OnClientClickas an attribute to the output. It is a property of the Button class, so simply doButton1.OnClientClick = "javascript: Purge();";