Button not firing event on ASP.NET control Programmatically - c#

I'm creating a Button on a ComboxChanged Event,
Button btn = new Button();
btn.ID = "btnNum1";
btn.Text = "Edit";
btn.Click += btnTest_Click;
pnl.Controls.Add(btn);
The event code is as followed
public void btnTest_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
Response.Write(btn.ID);
Response.Redirect("Page2.aspx");
}
I have tried, both Response.Write and Response.Redirect. None of them, works.
Same page gets refreshed. Does any one has any idea.
Button has to be created Dynamically, hence I can't try the Page_Init
I have also tried the CommandArgument event that also didn't work.
Any idea.

As Mt. Schneiders has mentioned in his comments under your question - if you dynamically add a control to a page, you must re-add it on the post-back. Just because you've added it as part of the event handler, does not mean that ASP.NET automatically creates the control on the post-back.
You need to store in the page the fact that the control was created - my personal preference would be to put the code in it's own function and set a ViewState value...
private void CreateButton()
{
Button btn = new Button();
btn.ID = "btnNum1";
btn.Text = "Edit";
btn.Click += btnTest_Click;
pnl.Controls.Add(btn);
ViewState["buttonAdded"] = true;
}
And call the function from your ComboxChanged event.
Then, on the Page_Load, you need to check to see if the button was added previously...
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack && ViewState["buttonAdded"] != null)
{
CreateButton()
}
}
(Note, I've stated Page_Load rather than Page_Init because the ViewState is not created at the Page_Init stage of the ASP.NET page life cycle)

when u added ur dynamic event handler it will store in particular control view state so when the page post back happened it will lose that event handler so u can implement load view state method which will come with page events code should be like
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
}

Try this btn.Click += new EventHandler(btnTest_Click);.
Button btn = new Button();
btn.ID = "btnNum1";
btn.Text = "Edit";
btn.Click += new EventHandler(btnTest_Click);
pnl.Controls.Add(btn);

Assume this is the code that create the button :
If ddl.SelectedIndex > 0 Then
Dim b As New Button
b.ID = "mybutton"
b.Text = "i'm a button"
panel.Controls.Add(b)
AddHandler b.Click, AddressOf Button_Click
End If
Note the AddHandler ok it is exactly what you're looking for then
Private Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim b As Button = CType(sender, Button)
Dim l As Label = CType(Me.FindControl("testlabel"), Label)
l.Text = b.Text & " my id is " & b.ID.ToString
End Sub
that's all :)

Related

Adding "OnClick" event to code behind button

So I've created a button, and I want to change its text by clicking on it.
This is my code behind (this is from the Page_Load code) :
Button InviteToGameBTN = new Button();
InviteToGameBTN.Click += new EventHandler(InviteToGameBTN_OnClick);
.
protected void InviteToGameBTN_OnClick(object sender,EventArgs e)
{
Button b1 = (Button)sender;
b1.Text = "Text changed";
}
What could be wrong ?
Thanks to all.
Not sure if this will 100% work but you may be able to use InviteToGameBTN.text to directly change it:
var button = FindViewById<Button>(Resource.Id.button1);
button.Click += delegate
{
button.Text = "changed text";
};
This was my little bit that I made in a new program, doesn't use an event handler but it uses the button.text to directly change its properties through the delegate { }

Dynamic button in asp.net - EventHandler is not fired

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.

Determining the source of the click event dynamically

I have a set of buttons that are added dynamically. As the user keeps clicking the buttons, new buttons are added to the window. I am using a winforms. I am binding the onclick event of all these buttons to the same function. I am using the following code.
System.EventHandler myEventHandle= new System.EventHandler(this.Button_Clicked);
Once a new dynamic button is created I add the event handler with the following code:
b1.Click += myEventHandle;
Now in the function Button_Clicked() I want to get the Button which invoked this event. I want to disable this Button so that it cannot be clicked again and I want the name of the Button that was clicked as I want to do various actions depending on button name. I am newbie in C#.
This is what I have tried so far, but doesn't seem to work:
Button b = sender as System.Windows.Forms.Button;
b.Font = new Font(b.Font, FontStyle.Bold);
Console.WriteLine(""+b.Name);
b.Enabled = false;
Use the sender of the event
if(sender is Button)
{
Button b = sender as Button;
b.Enabled = false;
///something = b.Name;
}
Well, your Button_Clicked method must look like
void Button_Clicked(object sender, EventArgs e) {
Button clickedButton = (Button)sender;//if sender is always a Button
clickedButton.Enabled = false;
}

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
});
});

Dynamically generated buttons, on click not being executed

I need to generate a dynamic list of buttons, I already did, with an event handler attached to it.
However the event handler is not being executed.
private void GetOptions(EcoBonusRequest request)
{
var ecobonuswworkflow = WorkflowFactory.CreateEcobonusWorkflow();
ecobonuswworkflow.SetCurrentStep(request.CurrentStatus);
var currentoptions = ecobonuswworkflow.GetCurrentOptions();
foreach(var option in currentoptions)
{
var btn = new Button() {Text = option.OptionName};
btn.Click +=new EventHandler(btn_Click);
Buttons.Controls.Add(btn);
}
}
void btn_Click(object sender, EventArgs e)
{
var btn = (Button) sender;
string command = btn.Text;
EcoBonusRequest request = this.GetDBRequest(RequestBaseId.Value);
EcoBonusRequestBL.AddWorkflowHistoryItem(request, command,CurrentUser, command);
}
The controls that you add dynamically in your page must be added in Page_init event, and they must have unique Ids. If you are adding textboxes or some other controls where user can input or change value, than on every post back when these controls are re-added they must have same IDs.

Categories