C# / apsx.net - Dynamically created button doesn't work - c#

Here is my problem: I had dynamically created some buttons in my page (in the Page_PreInit method), all linked to the same event handler. But those buttons don't fire the event when I click on them... Can someone help me?
Here is some of my code:
Button creation (on a foreach loop on the Page_PreInit method):
Button b = new Button();
field.Controls.Add(b);
b.Text = "Download";
b.ID = tmp_out[type] as String;
b.Click += new EventHandler(Download_Click);
The OnClick method:
private void Download_Click(object sender, EventArgs e)
{
//doing some stuff
}

Dynamic controls must be added during Page PreInit or Init, not on load. This is because of page lifecycle and viewstate loading... so try that first to see if that solves the problem.
Also, I believe I read that it's best to order your code this way:
Button b = new Button();
field.Controls.Add(b);
b.Text = "Download";
b.ID = tmp_out[type] as String;
b.Click += new EventHandler(Download_Click);
Adding the control first to the inner collection, then changing it's properties.

your event handler statement is
b.Click += new EventHandler(Download_Click);
but your method is
private void Download_Command(object sender, CommandEventArgs e)
are you sure its the right method to be triggered?

Should not be like this?
...
b.Click += new EventHandler(Download_Command);
...
private void Download_Command(object sender, EventArgs e)
{
//doing some stuff
}

Ok I solved my problem.
The ids of the buttons was containing some '\'. I just removed those '\' and it works just fine.
Thanks all for your reply!

Related

My page behind code created button onclick function isnt working

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.

Create a submit button when I press Add, multiple events under one button

Any idea how I could make a click event create another button with different click event?
I have a WPF app to make using EF. So I'm stuck at the part where I need to press button "Add" which will freeze other buttons and then create another button "Submit" with code for adding data to the table. I have tried some advice from msdn, but it doesn't work. Here is the code (previously in XAML added a button named b1):
public partial class RoutedEventAddRemoveHandler {
void MakeButton(object sender, RoutedEventArgs e)
{
Button b2 = new Button();
b2.Content = "New Button";
// Associate event handler to the button. You can remove the event
// handler using "-=" syntax rather than "+=".
b2.Click += new RoutedEventHandler(Onb2Click);
root.Children.Insert(root.Children.Count, b2);
DockPanel.SetDock(b2, Dock.Top);
text1.Text = "Now click the second button...";
b1.IsEnabled = false;
}
void Onb2Click(object sender, RoutedEventArgs e)
{
text1.Text = "New Button (b2) Was Clicked!!";
}
I even tried the most obvious solution to simply create another button with click event directly in click event.
I would recommend an alternative approach and put the submitbutton in your xaml code right away but make it so that it is invisible and disabled.
Then in the event handler you simply have to make it visible and enable it.
Your event handler that handles the submit, the dynamic creation of the button, hooking it in the form and such can all be avoided and don't have to be done at runtime.
This will result in a lot better readable code and maintainable code than your original approach unless you have a very good reason for it.
I have done the following coding and it is working for me
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
Button oButton = new Button();
oButton.Name = "btnMessage";
oButton.Content = "Message Show";
oButton.Height = 50;
oButton.Width = 50;
oButton.Click += new RoutedEventHandler(oButton_Click);
//root is a stack panel
root.Children.Insert(root.Children.Count, oButton);
DockPanel.SetDock(oButton, Dock.Top);
}
void oButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello World !");
}

Dynamically create buttons and add events to it

I need to dynamically create buttons (one for loop) and add "onClick" and "doubuleClick" events on it.
I did it like this:
Button bt = new Button();
bt.Click += bt_Click;
bt.DoubleClick += bt_DoubleClick;
private void bt_Click(object sender, EventArgs e)
{
label1.Text = this.Text;
}
private void bt_DoubleClick(object sender, EventArgs e)
{
//some code
}
First: My "bt_Click" method gets "main form" text in "label1". In debugger I see that sender is a button. What is wrong with it?
Second: My "bt_DoubleClick" event do not react at all, am I doing something wrong here?
Any help is appreciated.
You should cast sender to Button to get the bt.Text:
Button bt = new Button();
bt.Click += bt_Click;
bt.Text = "click me";
bt.Location = new Point(100,100);
this.Controls.Add(bt);
private void bt_Click(object sender, EventArgs e)
{
label1.Text = (sender as Button).Text;
}
Buttons doesn't react to double click event. You can read it here in detail.
In response to the first question, if I understand you correctly, in this.Text, this refers to the form because the method bt_Click is a member of the Main Form class. I think you might have meant to do:
private void bt_Click(object sender, EventArgs e)
{
label1.Text = (Button)sender.Text;
}
Second: Is this just a case of the bt_Click handler firing twice?
The easiest way to do this it is to use "datagrid".
Datagread has the great support for all events and for organization of items (image, text and so on).
I have made "save" or "open" dialog form to browse content from remote SFTP server, very easy with datagrad, but I had a problem to do it with buttons or labels.

Button created after PageLoad - Click Event not firing

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

How Do I Add Event Handlers to .NET Buttons Programmatically?

I'm trying to employ the strongest OOP I can muster in developing a web application, but I'm having issues adding event handlers to my objects as I create them using code. I'm sure it's a fairly simple solution that I just keep passing up, but I'm at a loss as to what to try next. Below is some test code I've been playing with, just trying to get a button press to go do something.
(Imagine there's a break point on the line "int i;")
Button b = new Button();
b.Text = "Do Something";
b.Attributes.Add("runat", "server");
b.Attributes.Add("OnClick", "click");
form1.Controls.Add(b);
private void click(object sender, EventArgs e)
{
int i;
}
Since this is a new button created by my Page_Load, I can't just hardcode the XHTML. Debugging never hits my breakpoint. I haven't had any more success with CheckBoxes either.
You have to subscribe to the Click event:
Button b = new Button();
b.Text = "Do Something";
b.Click += click;
form1.Controls.Add(b);
private void click(object sender, EventArgs e)
{
int i;
}
By adding the onclick Attribute to the Button's Attributes collection, it will be rendered as an attribute on the HTML input tag. In that case you could use it to execute some javascript code on the client side.
b.Attributes.Add("onclick", "alert('Hey')");
//Will render the button as
<input type="submit" name="x" value="Do Something" onclick="alert('Hey')">
You can do:
Button b = new Button();
b.Text = "Do Something";
b.Click += new EventHandler((s, ev) =>
{
int i;
});
form1.Controls.Add(b);

Categories

Resources