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

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

Related

C# - Associate panel to button when created programmatically

I wanna make an example application in C# to show to my classmates(I'm 10th grade) how would a Wireless Device Controller Interface work. I know how to write most of the program, but I don't know how to do one thing.
I wanna create a button programmatically and once it is created, associate to it a panel that will show and hide when that button is clicked. Can someone help me?
I forgot to tell you something. The panel needs to be created programmatically too.
Create panel:
var panel = new Panel();
this.Controls.Add(panel);
Create button:
var button = new Button();
this.Controls.Add(button);
Add event handler to button:
button.Click += (o,e) =>
{
panel.Visible = !panel.Visible;
};
Is the Panel also created dynamically? – Idle_Mind
#Idle_Mind yes, it is. I forgot to mention it – DannyDSB Official
The easiest way is to simply store a reference to the Panel in the Tag() property of the Button. Here's a silly example:
private void button1_Click(object sender, EventArgs e)
{
Panel pnl = new Panel();
pnl.BorderStyle = BorderStyle.FixedSingle;
pnl.BackColor = Color.Red;
Button btn = new Button();
btn.Text = "Toggle Panel";
btn.Tag = pnl;
btn.Click += delegate {
Panel p = (Panel)btn.Tag;
p.Visible = !p.Visible;
};
flowLayoutPanel1.Controls.Add(btn);
flowLayoutPanel1.Controls.Add(pnl);
}
First you need the name of the panel. You need to set its visibility property to change the visibility (duh.)
To do that on a button click, you need to attach an event handler to it. Let's first assume that you called your newly created button "myButton" for simplicities sake.
First you create the handler function
void myButton_Click(object sender, RoutedEventArgs e){
panel.visibility = whatever;
}
and later assign the function to the click handler with
myButton.Click += myButton_Click;

How to create an asp:button programmatically in c# behind with click handling

i write this code after many search but is not working
i need to create as asp:button programmatically and handling it
for(int i=0;i<DtShow.Rows.Count;i++)
{
Button btn = new Button
{
Text = "حذف",
ID = i.ToString(),
UseSubmitBehavior = false,
CommandArgument =i.ToString(),
CssClass = "btn btn-danger"
};
btn.Click +=new EventHandler(this.btn_Click);
lstAccessDgv.Rows[i].Cells[2].Controls.Add(btn);
}
protected void btn_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
int id = Convert.ToInt32(b.ID);
DtCode.Rows.RemoveAt(id);
DtShow.Rows.RemoveAt(id);
lstAccessDgv.Rows[id].Visible = false;
}
why not call btn_Click?
Unfortunately your question doesn't make it clear what information you're looking for, however, since you did make a specific query, I'll address that.
why not call btn_Click?
Because the btn_Click event handler hasn't been bound to the button's click event.
That's why you need to do this when you create the button:
btn.Click +=new EventHandler(this.btn_Click);
This executes btn_Click when the button is clicked.
A thing to keep in mind, though, is that this function will execute for every button in the list so you need to make sure it does work that specifically relates to the list item to which the button belongs.

Set button handle in C#

btnName1 = new Button();
counter++;
//Start setting of Button
btnName1.Location = new Point(47, 35 + a);
btnName1.Size = new Size(132, 59);
btnName1.FlatStyle = FlatStyle.Popup;
btnName1.Text = textBox1.Text;
btnName1.Name = "btn" + counter.ToString();
btnName1.BackColor = Color.White;
btnName1.ForeColor = Color.Black;
panel1.Controls.Add(btnName1);
a += btnName1.Size.Height + 2;
btnName1.Click += BtnName1_Click;
I wrote this code for making a new button. When I click on add button this code runs and by each click on add button we can make new button.
But my problem is this
How can I set click handle for each button? I mean when I click on each button, they show their text to me
and I wrote this code to make the texts different:
btnName1.Text = textBox1.Text;
You didn't post your event code, but as Steve mentioned in his comment (that appears to have since been removed), you can use the sender argument to get the particular button that was clicked. Something like the following should be what you're after:
private void BtnName1_Click(object sender, EventArgs e)
{
//Access the text with: (sender as Button).Text
//Example: Write this button's text to the debug output window
Debug.WriteLine((sender as Button).Text);
}
Just be careful that in my specific example, you're only subscribing a Button to this event.
Prefered way is what you've put so far
btnName1.Click += BtnName1_Click;
...
private void BtnName1_Click(object sender, EventArgs e) {
// Button which has been clicked
Button button = sender as Button;
//TODO: put relevant code here
...
}
However, you can assign to each button its own event handler:
btnName1.Click += (s, e) => {
Button button = s as Button;
//TODO: put relevant code here
...
};

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

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

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!

Categories

Resources