Dynamic button in asp.net - EventHandler is not fired - c#

I created a button from code behind:
Panel dynamicPanel = new Panel();
Button dynamicButton = new Button();
dynamicButton.Text = "View";
dynamicButton.Click += new EventHandler(dynamicButton_Click);
dynamicPanel.Controls.Add(dynamicButton);
dynamicDiv.Controls.Add(dynamicPanel);
and the OnClick method:
protected void dynamicButton_Click(object sender, EventArgs e)
{
Response.Write("view button response");
string script = "alert(\"view clicked.\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
When I click the button, there is postback (IsPostback with Javascript alert) but the EventHandler is not fired. I can say that content that was visible on the page disappears if that is a clue.
I need to create this in a custom protected void method.

Your code looks a bit weird to me, but as for the problem "When I click the button, the method is not fired": Try renaming the method dynamicREGButton_Click() to dynamicButton_Click().
I assume you have a method dynamicButton_Click() in your code already; otherwise, you could not compile. However, the method you register via dynamicButton.Click += new EventHandler(...); is the method you call. The code you showed us doesn't match in that regard.

Related

Call C# code behind function from programatically created button

In my webform I created button from my code behind:
Button btnShowCase = new Button();
btnShowCase.ID = "btnShowCase_" + ticketNumber;
btnShowCase.CssClass = "BtnShowCase";
btnShowCase.Text = "Display";
btnShowCase.OnClientClick = "ShowCase";
On client click I want to execute function
protected void ShowCase(object sender, EventArgs e)
{
Do something
}
OnClientClick do not call ShowCase. What I am doing wrong?
Instead of
btnShowCase.OnClientClick = "ShowCase";
Try
btnShowCase.OnClick += ShowCase;
ClientClick invokes Javascript that runs within the browser; the string argument is the name of a Javascript function. Click causes a postback and invokes a server-side method; the argument is a method that matches the delegate for the event type.
OnClientClick is an event handler, and should be set like this:
btnShowCase.OnClientClick += "ShowCase";
instead of
btnShowCase.OnClientClick = "ShowCase";

Button Event Not Firing in WebControl

I'm attempting to create a "server control" that derives from WebControl. This needs to be done entirely in C# so that it can be compiled into a .dll. I am not interested in creating a user control with a .ascx file (I actually already have a "user control" but I want to add it to a library so I'm converting it).
My control is dead simple right now and I can't get a button event to fire:
public class ButtonWrapper : WebControl
{
protected Button button;
public event EventHandler<Events.GenericEventArgs<Tuple<int, string>>> ButtonClicked;
public void Button_Click(object o, EventArgs e)
{
ButtonClicked(this, new Tuple<int,string)(0, "abc"));
}
public void WHERE_DO_I_PUT_THIS_CODE()
{
button = new Button()
{
ID = "button",
Text = "Button"
};
button.Click += new EventHandler(Button_Click);
}
}
Where do I need to "create" the button? I currently have it in an overloaded CreateChildControls():
protected override void CreateChildControls()
{
this.Controls.Clear();
button = new Button()
{
ID = "button",
Text = "Button"
};
button.Click += new EventHandler(Button_Click);
this.Controls.Add(button);
this.ChildControlsCreated = true;
}
The control loads just fine, but when I click on the button, the page just refreshes and the event is never fired. I want to the button in ButtonWrapper to fire so that the parent page can listen. I think I'm close but I'm missing something simple.
Edit: I don't quite have the right event variables types for EventArgs passing and such when I was simplifying the problem for this question.
I created new solution and i tried it.
You can download from this link : http://dosya.co/download.php?id=51BACA121
I m at work and most of upload sites blocked. So i couldnt upload another site. If u cant download i can try find different upload site.

How to create an onClick eventHandler for a dynamically created button

Currently, I am doing a project for students' hostel and now I have to implement some search strategies about students.Here I have to create a button dynamically when the user clicks on the another server button in .aspx page and accordingly I have to create the onclick event handler for the newly created button. The code-snippet that I used is:
protected void btnsearchByName_Click(object sender, EventArgs e)
{
TextBox tbsearchByName = new TextBox();
Button btnsearchName = new Button();
tbsearchByName.Width = 250;
tbsearchByName.ID = "tbsearchByName";
tbsearchByName.Text = "Enter the full name of a student";
btnsearchName.ID = "btnsearchName";
btnsearchName.Text = "Search";
btnsearchName.Click += new EventHandler(this.btnsearchName_Click);
pnlsearchStudents.Controls.Add(tbsearchByName);
pnlsearchStudents.Controls.Add(btnsearchName);
}
protected void btnsearchName_Click(object sender, EventArgs e)
{
lblsearch.Text = "btnsearchName_Click event fired in " + DateTime.Now.ToString();
}
Here, the problem is newly created eventHandler doesnot get fired. I have gone through this site and looked several questions and answers and also gone through the page life-cycle and they all say that the dynamic button should be on Init or Pre_init, but my problem is I have to create it when another button is clicked, how can it be possible?
You need to add the click handler for the button on every postback.
you could look for the button in the search students panel on page load or try the page OnInit() method to add the handler when its created.
Also check here:
Dynamically added ASP.NET button click handler being ignored
and here:
asp.net dynamically button with event handler
and here:
asp:Button Click event not being fired
(all of which give similar suggestions)
Try this http://msdn.microsoft.com/ru-ru/library/system.web.ui.webcontrols.button.command(v=vs.90).aspx
btnsearchName.Command += new CommandEventHandler(this.btnsearchName_Click);
btnsearchName.CommandName = "Click";
You need to recreate the button and attach the event handler every time. For this, create a list of button and save it on session. On page load, go through the List and create the button every time
public Button create_button()
{
btnsearchName.ID = "btnsearchName";
btnsearchName.Text = "Search";
btnsearchName.Click += new EventHandler(this.btnsearchName_Click);
return btnsearchName;
}
public TextBox create_textbox()
{
TextBox tbsearchByName = new TextBox();
Button btnsearchName = new Button();
tbsearchByName.Width = 250;
tbsearchByName.ID = "tbsearchByName";
tbsearchByName.Text = "Enter the full name of a student";
return tbsearchByName;
}
protected void btnsearchByName_Click(object sender, EventArgs e)
{
TextBox tbsearchByName = create_textbox();
Button btnsearchName = create_button();
//add to panels
pnlsearchStudents.Controls.Add(tbsearchByName);
pnlsearchStudents.Controls.Add(btnsearchName);
//add to session
List<Button> lstbutton = Session["btn"] as List<Button>
lstbutton.add(btnsearchName);
//similarly add textbox
//again add to session
Session["btn"] = lstbutton
}
public override page_load(object sender, eventargs e)
{
//fetch from session, the lstButton and TextBox and recreate them
List<Button> lstbutton = Session["btn"] as List<Button>;
foreach(Button b in lstbutton)
pnlsearchStudents.Controls.Add(b);
//similar for textbox
}
I am not sure but may be you have to override the OnInit() method like this.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
You just need to add this code on ready state of jquery code and it will work fine for the dynamic button too
$(document).ready(function(){
$('input#tbsearchByName').click(function(){
// code goes here
});
});

Can't call Click Event on dynamic button

I want to create a method in code behind that creates a button and places it in a PlaceHolder. I want this button to have a Click event.
After calling the "test" method button is placed correctly but the click event is not called.
private void test()
{
Button linkBtn1 = new Button();
linkBtn1.Text = "linkBtn1";
linkBtn1.OnClientClick = "return false;";
linkBtn1.Click += new EventHandler(linkBtn1_Click);
PagesPlaceHolder.Controls.Add(linkBtn1);
}
void linkBtn1_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
Removing the OnClientClick = "return false;" is necessary but not sufficient to get this to work. If you want the event handler on the dynamically added button to be triggered, you'll need to add this button every time the page loads.
One simple way would be to save the fact that the button has been added in ViewState, and then check that on PageLoad, and re-add the button if needed.
Here's a sample that works for me (and throws the exception when clicked)
protected void Page_Load(object sender, EventArgs e)
{
//if the button was added previously, add it again
if (ViewState["Added"] != null && (bool)ViewState["Added"])
addButton();
}
//this is the method that adds the button
protected void add_Click(object sender, EventArgs e) {
ViewState["Added"] = true;
addButton();
}
private void addButton() {
Button linkBtn1 = new Button();
linkBtn1.Text = "linkBtn1";
linkBtn1.Click += new EventHandler(linkBtn1_Click);
placeholder1.Controls.Add(linkBtn1);
}
void linkBtn1_Click(object sender, EventArgs e) {
throw new Exception("Button Click Event Triggered. Hello yellow screen!!!");
}
As #oleksii points out, have the clientside code is returning false so the form never gets submitted. You need to comment this out, then your event handler should fire.

disable "cause validation" for dynamically created buttons

I am creating the same button twice: once on Page_Load, and another on: Page_PreRender.
I expected to see the same behavior, however, the buttons created on Page_PreRender doesn't work the way intended. (i.e. property "causeValidation" remains true).
"I want to disable "causeValidation" for the button in page_preRender, and i want it there in PreRender. Also, I want the Button_Click function to execute for both buttons, currently it does only for button created on "Page_load" ".
I am looking for a solution or an explanation for this behavior.
Thank You.
Take a look at the code:
protected void Page_Load(object sender, EventArgs e)
{
form1.Controls.Add(GetButton("Button1", "Click"));
}
protected void page_PreRender(object sender, EventArgs e)
{
form1.Controls.Add(GetButton("Button3", "Click"));
}
private Button GetButton(string id, string name)
{
Button b = new Button();
b.Text = name;
b.ID = id;
b.CausesValidation = false;
b.Click += new EventHandler(Button_Click);
b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
return b;
}
protected void Button_Click(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), ((Button)sender).ID, "<script>alert('Button_Click');</script>");
Response.Write(DateTime.Now.ToString() + ": " + ((Button)sender).ID + " was clicked");
}
and here is the javascript:
<script type="text/javascript">
function ButtonClick(buttonId) {
alert("Button " + buttonId + " clicked from javascript");
}
</script>
Update:
let me add this: Both buttons execute the client's script. This means that buttons are created. "see function GetButton() ".
Also, the reason why i have the button created "on preRender" instead of "on Page_Load" is that: if i have a form used to enter data into a table dynamically, and i add the data on button click, the the page will PostBack first, then execute the event handler, (i.e the data is added to the table but will show on NEXT postBack). So, PreRender is used to show the table AFTER it is updated by the button_click event.
I hope this addition is useful
As you see from this image, that represents asp.net page life cycle (copied from MSDN), Event Handling precedes PreRender. So, in order to fire Button_Click the button itself has to be created before the Event Handling. Page PreInit is a preferred place to add dynamic controls.
you can see it yourself, just add breakpoints at Page_Load, Page_PreRender, Button_Click. notice the order there are triggered?
Check asp.net page lifecycle: events are handled after page load and before PreRender.
ASP.NET cannot handle an event involving a control that does not yet exists.

Categories