I would like to know , how it is able to identify, which button is clicked, if i have 3 buttons.
Thanks & regards
I don't know anything about your program, other than it having 3 buttons. So, here are our buttons:
Button b1 = new Button();
b1.Name = b1.Text = "Button 1";
Button b2 = new Button();
b2.Name = b2.Text = "Button 2";
Button b3 = new Button();
b3.Name = b3.Text = "Button 3";
Now each button needs to open a messagebox displaying their name when clicked. This is where we're going to use Button_Click event. Each button's Click event can have an unique method which is being called when the button is clicked, or all the buttons can use the same method. I'll provide you with both ways.
Method 1: Same method for each button. This method is going to do nothing but display the pressed button's name.
private void Global_Button_Click(object sender, EventArgs e)
{
MessageBox.Show(((Button)sender).Name + " was pressed!");
}
Whenever a button is clicked, this method gets called and the button is given as object sender parameter. Notice that we must cast it to (Button)sender before using it as a button.
There's still one thing to do. This doesn't get called automatically for each button, it's just a method. Instead, we must tell our buttons to call this when they're clicked. This is what events are for:
b1.Click += Global_Button_Click;
b2.Click += Global_Button_Click;
b3.Click += Global_Button_Click;
Method 2: Unique method for each button. This method is only required if your buttons do more than just print the name of the button. So, if the button click needs to do something unique for different buttons, use this.
It works the same as method one, but instead of defining one method for all buttons, we define 3 methods, one for each.
private void Button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Button 1 was pressed!");
// here you can add more code which will be executed when button 1 is clicked
}
private void Button2_Click(object sender, EventArgs e)
{
MessageBox.Show("Button 2 was pressed!");
// code for button 2
}
private void Button3_Click(object sender, EventArgs e)
{
MessageBox.Show("Button 3 was pressed!");
// code for button 3
}
Now lastly we need to tell the buttons to use these methods when they're clicked, and again we use events. This time, different method for each button:
b1.Click += Button1_Click;
b2.Click += Button2_Click;
b3.Click += Button3_Click;
Usually the buttons have seperate event handlers but in case you have three buttons sharing the same event handler, then use command name/command arguments to differentiate between them. The event handler will have an CommandEventArgs through which you can collect the command names and command arguments
Related
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 !");
}
I have 10 buttons, 0-9 (button0, button1, button2...). When I click any of these buttons, I would like to perform the same routine on them. I would like to know how to, upon clicking of any of these buttons, direct them to the routine below.
private void button0_Click(object sender, EventArgs e)
{
int newValue;
newValue = Convert.ToInt32(Button.text);
}
I have already gone into the properties of each button, then events, and changed the click event to button0_Click (I would have thought this would add "handles button1.click, button2.click, etc." after "private void button0_Click(object sender, EventArgs e)" but if it does that in the background, that's ok as long as it works.)
I also need to know how to identify the button that has been pressed, which is where I'm at with "Convert.ToInt32(Button.text)" (e.g. button2.text = "2").
You can select the same event handler for all the buttons in the designer (in the event tab of the properties window, select the event and there'll be a drop down with all your defined event handlers).
To get which button has been clicked on, cast the sender argument to a Button and you'll have it.
Button button = (Button)sender;
int value = int.Parse( button.Text );
Edit: Also, the "Handles control.event" syntax only exists in Visual Basic.
Edit: Check out the generated code (Form1.Designer.cs, for example) to see how the events are hooked up.
The C# language doesn't use handles to bind events (as VB does). The code for the actual binding is in the generated code for the form, i.e. in the background as you put it.
The sender property is a reference to the control where the event happened. You just need to cast it to the actual type of the control:
private void button0_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
int newValue = Convert.ToInt32(button.text);
}
As an alternative to using the text of the button (for example if you want to translate the application to different languages, or simply don't want to rely on the text), you can put whatever you like in the Tag property of each button, and retrieve it in the event handler.
You could wire them all up to the same event handler an extract the button from sender e.g.
private void button0_Click(object sender, EventArgs e)
{
var button = sender as Button
if (button != null)
{
int newValue = Convert.ToInt32(Button.text);
}
}
Basically, I have an update panel in which i have a link button, when user clicks on the link button all the contents are cleared and textbox shows up in which user enters something and when user hit enter key, the update panel should be refreshed or gets updated or repopulated with all the contents .
How can I do it ???
The way I am trying to do this is that when event handler of link button is fired, I created a hidden button dynamically and assign it a new event handler which will get fired when user hits enter key.This new dynamic button is created inside link button event handler. In this new button event handler I will repopulate the contents back.
The problem with my way is the event handler of dynamically created button is not fired.
Why ???
Please try to answer in c#.
Thanks in advance.
Regards,
My code #
protected void Submit_Click1(object sender, EventArgs e)
{
Label1.Text = TextBox1.Text + TextBox2.Text + " are sucessfully registered";
Button mento = new Button();
mento.cssclass = "invisible";
mento.Click += new EventHandler(mento_click);
// here this new mento button is attached to update panel
updatepanel1.ContentTemplateContainer.Controls.add(mento);
}
Now the problem is mento_click event handler does not get fired ???
You can catch the enter key, in the textbox?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//add event keydown
textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
}
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode )
{
case Keys.Enter:
//YOur updatecode here:
MessageBox.Show("You press enter");
break;
default:
break;
}
}
}
You have to attach the event on page_init or page_load every time theres a request, or the event wont get hooked up to the control.
you can check out this link to understand why:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
Example
if you want to hook it up on the submit you should do something like:
page_init(object sender, EventArgs e)
{
CreateControls();
}
private void CreateControls()
{
//Create button with event and add to the panel
}
clickEvent(object sender, EventArgs e)
{
updatePanel.Update();
}
That should fire correctly the event. Im sorry i just wrote this on the fly and didnt test it, but i hope it gives you de general idea.
Cheers.
To all of you strugling with postback from buttons in asp.net, I would like to mention an alternative and ancient method of dealing with button-click events.
1) name your dynamically created buttons using a Prefix (like for instance this one: btn_). That way, every button you create will have a name starting with this prefix. For example the first button you create will have the name btn_0. You can achieve this by a routine like this one:
For _counter As Integer = 0 To 3
Dim butt As New Button
' the next 1 line is convenient when programming for the .net 4.0 framework:
butt.ClientIDMode = UI.ClientIDMode.Static
butt.butt.ID = "btn_" & _counter
butt.Text = "someting"
page.controls.add(butt)
next
2) ... and then, to handle it all, you can do it like this in the on_load event of your asp.net page:
If IsPostBack Then
For Each key As String In Request.Form
If InStr(Trim(key), "btn_") > 0 Then
Response.Write(Request.Form(key))
End If
Next
End If
My problem is I have two labels and two buttons in two different update panel in ASP.Net. The update panels contains two buttons. When buttons are clicked it will update the corresponding label text. The issue is, suppose I gave a delay of 5 seconds in my button1_click() method, when I click button1 and button2 immediately, label2 is gettin updated, whereas label1 is not getting updated.
Can you suggest where I'm going wrong?
protected void Button1_Click2(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
Label1.Text = "Hello";
}
protected void Button2_Click1(object sender, EventArgs e)
{
Label2.Text = "World";
}
In the Button Click Event, Update the Update Panel where the Second Label presents like below:
UpdatePanel2.Update();
I am developing a C# WinForms application. On the FormLoad event, I dynamically create and add to the form 100 buttons without text, but with names like button1, button2 etc. Also, onto these buttons, after their creation, I dynamically link a unique event handler for the ButtonClick event. How can I access the button's properties from within the event handler (more specifically the button name)?
If I use this.Name, I get the name of the form, and not the name of the button.
Later Edit: (for those who might wonder here in search of solutions)
private void function1()
{
Button a = new Button();
a.Name = "button" + (i * j).ToString();
a.Click += new EventHandler(OnFieldButtonClicked);
}
private void OnFieldButtonClicked(object sender, EventArgs e)
{
Button button = (Button)sender;
MessageBox.Show(button.Name);
}
The sender argument is the event handler encapsulates an instance of the object that has triggered the event:
Button button = (Button) sender;
String text = button.Text;