I have created button manually from the behind code page using asp.net WebForms.
That is the creation code:
Button myButton = new Button();
myButton.ID = "b" + arrcodes[i];
myButton.Text = "Buy Now!";
myButton.CssClass = "btn-primary";
myButton.Click += new EventHandler(myButton_Click);
myPlaceHolder.Controls.Add(myButton);
I googled how to add onClick function and used method which founded here in stackoverflow. But this method not working.. the function "myButton_Click" isnt activated when i press the button.
protected void myButton_Click(object sender, EventArgs e)
{ // my code }
Have i did something wrong?
You will need to reload that dynamically created button on postback with same Id inside Page_Init or Page_Load event.
Otherwise, it won't be in the Control Tree, and cannot trigger the Click event.
For example,
public partial class Default : System.Web.UI.Page
{
protected void Page_Init()
{
CreateButton();
}
protected void myButton_Click(object sender, EventArgs e)
{
}
private void CreateButton()
{
Button myButton = new Button();
myButton.ID = "b1";
myButton.Text = "Buy Now!";
myButton.CssClass = "btn-primary";
myButton.Click += new EventHandler(myButton_Click);
myPlaceHolder.Controls.Add(myButton);
}
}
Usually, the better option is to create the button and toggle it's visibility.
If you really need to create it dynamically, make sure you're creating the button in OnInit method for event handler to work.
Related
My intention is to create buttons at runtime and have a click event handler subscribed to them. Once the dynamically created button is clicked, the click eventhandler is unsubscribed, such that the click event only fires once.
At runtime the desired behaviour only works if I create one button and click it immediately . If I create more than one button, than only the last created button unsubscribes from the click event. Did I miss something?
public partial class Form1 : Form
{
Button b;
int counter;
public Form1()
{
InitializeComponent();
}
// create more buttons
private void button1_Click(object sender, EventArgs e)
{
b = new Button();
b.Size = new Size(50, 50);
b.Click += b_Click; // dynamic button click event
this.Controls["flowLayoutPanel"].Controls.Add(b);
}
// dynamic button click eventhandler
void b_Click(object sender, EventArgs e)
{
b.Text = counter.ToString();
b.Click -= b_Click;
counter++;
}
}
Because b member will reference last created dynamic button, so clicking any buttons will remove click event handler of currently referenced button in b variable, which would be last created.
Use sender to access instance of "current" button and remove click event handler only from "current" button.
void b_Click(object sender, EventArgs e)
{
var button = sender As Button;
button.Text = counter.ToString();
button.Click -= b_Click;
counter++;
}
Don't use private member for dynamic button, but local variable
private void button1_Click(object sender, EventArgs e)
{
var button = new Button();
button.Size = new Size(50, 50);
button.Click += b_Click;
this.Controls["flowLayoutPanel"].Controls.Add(button);
}
If you need to reference collection of created button somewhere, you can access them from the controls of flow panel where buttons were added
var dynamicButtons = .
this.Controls["flowLayoutPanel"].Controls.OfType<Button>().ToList();
Or save them to the dedicated collection (in case flow panel has other buttons)
I want to use PerformClick() in asp.net webforma but found that can't be used. Any replacement for this PerformClick. I also have write the code as below but still have no idea. Thank you.
protected void Page_Load(object sender, EventArgs e)
{
}
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.ButtonEnter.Click += new System.EventHandler(this.ButtonEnter_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
Button.PerformClick() has namespace System.Windows.Forms, therefore you can't use it in ASPX page's code behind.
Assumed ButtonEnter is a button server control, you can simulate button click programmatically in 2 ways:
1) Direct calling server-side Click event handler method
ButtonEnter.Click(sender, eventArgs);
Note: Adjust both sender & eventArgs arguments depending on your requirements.
2) Using client-side event handler & RegisterStartupScript
JS
function click() {
document.getElementById("<%= ButtonEnter.ClientID %>").click();
}
Code behind
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "Click", "click()", true);
Related issues:
Programmatically fire a button's click event
How to programmatically fire the input(button) onclick event
In my Sharepoint 2010 app, I'm handling most events client-side with jQuery. However, for the saving of data to the Sharepoint list, and the generation of a PDF file with that data, I want to handle that server-side, with C#.
I tried to invoke a C# event this way:
0) Aded an HTML button in my project's *.ascx file:
<button type="button" name="saveData" id="saveData">Save Data</button>
1) Added jQuery to respond to that button being clicked (in the same *.ascx file):
$("#saveData").click(function () {
$('#hiddenSave').trigger('valuechanged');
});
2) Created a hidden element in the server-side C# (in the *.ascx.cs file):
HiddenField hiddenSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
hiddenSave = new HiddenField();
hiddenSave.ID = "hiddenSave";
hiddenSave.ValueChanged += new EventHandler(hiddenSave_ValueChanged);
this.Controls.Add(hiddenSave);
}
protected void hiddenSave_ValueChanged(object sender, EventArgs e)
{
GeneratePDF();
}
private void GeneratePDF()
{
;//bla
}
But I never reach the "ValueChanged" event handler; $("#saveData").click() fires, but not hiddenSave_ValueChanged().
So do I need a tweak to this, or a completely different approach? How can I do as much as possible client-side with jQuery, but also run server-side/C# code where necessary, in a Sharepoint 2010 app?
UPDATE
A little more detail, and about additional things I've tried: I'm creating a button on a Sharepoint page dynamically (in C#) in my *.ascx.cs file:
Button btnSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
btnSave.Visible = false;
this.Controls.Add(btnSave);
}
protected void btnSave_Click(object sender, EventArgs e)
{
btnSave.Text = "You clicked me!";
PostTravelData ptd = new PostTravelData();
}
I set it visible at the right time in the client-side jQuery in the *.ascx file:
$('#btnSave').show();
However, clicking the button does not reach the btnSave_Click() event - the breakpoint there is never reached, nor is the button's text changed. Why not?
Even when I don't set the button invisible (comment out the "btnSave.Visible = false;" line), the click handler isn't reached...is Page_Load() too late? Is there an earlier page event I can use that would work?
I tried moving it from Page_Load() to OnPreRender(), too, like this:
protected void OnPreRender(EventArgs e)
{
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
//btnSave.Visible = false;
this.Controls.Add(btnSave);
}
...(and OnRender()) but the button doesn't even display...
And, trying a different tack, I commented out the dynamic creation server-side code and tried to attach to a button created in the HTML (*.ascx file):
<button type="button" name="saveData" id="saveData" runat="server" onclick="saveData_Click">Save Data</button>
(by adding the "runat server" and the onclick handler), and then adding this "code-behind" (*.ascx.cs)):
protected void saveData_Click(object sender, EventArgs e)
{
PostTravelData ptd = new PostTravelData();
SaveToList(ptd);
GeneratePDF(ptd);
}
...but there was still no joy in Mudville -- the breakpoint in the handler is not reached.
Yet another attempt was:
In the *.ascx:
<asp:Button runat="server" id="saveData" name="saveData" onclick="saveData_Click" Text="Bla" />
In the code-behind:
saveData.Click += saveData_Click;
The "Bla" button is created, but clicking on it reaches not the breakpoint in the "saveData_Click" handler.
I even adapted some code from here like so:
Button btnSave = null;
. . .
protected override void CreateChildControls()
{
btnSave = new Button();
btnSave.Width = new Unit(150, UnitType.Pixel);
btnSave.Text = "Can you see me?";
btnSave.Click += new EventHandler(btnSave_Click);
Controls.Add(btnSave);
}
...but I still do not reach the "protected void btnSave_Click(object sender, EventArgs e)" handler when I click the button.
Surely there's a way to get a handle on the button server-side and manipulate it (specifically, respond to its click event)...?!?
First of all, as far as I know, there is no such event for input type hidden in a ascx page. If you create the input type hidden with runat server in the ascx code then you'll see that when you try to add this event it's not available. However there are other events like OnClick that you can simulate to get the desired result.
I am trying to call dynamically created button click event. I this event I want to show one message on clicking dynamically created button.
my Code
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnMain_Click(object sender, EventArgs e)
{
Button btnNew = new Button();
btnNew.ID = "btnClick";
btnNew.Text = "Click";
btnNew.Click += new System.EventHandler(btnNew_Click);
this.form1.Controls.Add(btnNew);
}
protected void btnNew_Click(object sender, EventArgs e)
{
Label lblMeaaseg = new Label();
lblMeaaseg.ID = "txtMessage";
lblMeaaseg.Text = "Hello Shree";
this.form1.Controls.Add(lblMeaaseg);
}
You create the dynamic button in the click event handler of btnMain during the postback caused by btnMain click. After that you see the new button in the browser page, click it and expect its click event handler (btnNew_Click) to fire. Pressing the new dynamic button causes a new postback that is processed by a new instance of the page created on the server by ASP.NET. This new page does not have the dynamic button - there is nothing there connected to btnNew_Click. You have to write code that persists the fact that the dynamic button has been created and recreates this button every time the page is instantiated. So that this button has a chance to feel and respond to its client-side click.
I have a button that is created after a user selects a certain value from a dropdown menu, but it is not firing its' EventHandler. Is there something with the Lifecycle, OnInit possibly, that I have to refresh for the handler to fire correctly?
Event fired from DropDownList's OnSelectedIndexChanged
protected void Selected_floor_first(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = "room_button_1";
btn.Text = "Select";
btn.Click += new EventHandler(room_1_Click);
floor_1_room_overlay.Controls.Add(btn);
}
Handler: (Not Firing)
protected void room_1_Click(object sender, EventArgs e)
{
validation.Text = "You selected a Room";
}
If you must create your button dynamically, create it inside the OnInit() method of the page.
Event handling happens after Page Init. So, the button will have to be created before Page Init, for the events to be handled.
As it is dynamically added, you have to take that code in Page_Init() event that occurs after every postback. otherwise when the postback occurs, there is no room_button_1 in the forms.controls collection and the event is missed. So
add it as it is being added.
after adding set a variable in session to identify that dynamic control has been added
on page_init() check the session variable of step2. if it says yes then create the control you created in step 1.
Instead of repeating the code, it's better if you create a function for button creation and call it from your Select_floor_first() and Page_Init().
The button goes out of scope mate. define it as a private variable otherwise the event wont fire as the button disposed after Selected_floor_first method finishes
private Button btn = new Button();
protected void Selected_floor_first(object sender, EventArgs e)
{
btn.ID = "room_button_1";
btn.Text = "Select";
btn.Click += new EventHandler(room_1_Click);
floor_1_room_overlay.Controls.Add(btn);
}
protected void room_1_Click(object sender, EventArgs e)
{
validation.Text = "You selected a Room";
}