Dynamically create buttons and add events to it - c#

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.

Related

How to make buttons display their text in a label using one click event

Is it possible to have a click event that displays the text of buttons in a label in c#.
I want to write single code that will work for:
public button1_Click(Object sender, EventArgs e){
label1.Text = button1.Text;
}
public button2_Click(Object sender, EventArgs e){
label2.Text = button2.Text;
}
Is this what you are looking for?
On a button click, you can handle setting text as below
you can add two buttons. Have same click events for both buttons.
Take help of parameter sender to get which button is clicked.
code (sender as Button) gives you all the details of clicked button.
private void button1_Click(object sender, EventArgs e)
{
this.label1.Text = (sender as Button).Text;
}
1) Add a Button and a Label to the blank Form in a new project.
2) Double-click the Button.
This will generate the following Click event method...
private void button1_Click(object sender, EventArgs e) {
}
3) Put the following line of code in the button1_Click method body:
label1.Text = button1.Text;
4) Profit.

one Click event for multiple buttons with Text property

I want to make a click event for a bunch of buttons. The problem is that I want to use the button's Text, and pass it to a function. Now the click event is passed a object sender. When I tried changing that to Button sender, it gave errors. But I don't know how else I can work with the senders Text.
Here is the normal code, which gave a single error:
private void guess_Click(object sender, EventArgs e)
{
guess(sender.Text);
}
I changed it to this, which gave errors:
private void guess_Click(Button sender, EventArgs e)
{
guess(sender.Text);
}
Question:
How can I work with the Button's Text property within this click event, which is a single click_event for multiple buttons?
Step 1: You need to subscribe to the Button Click event of all your buttons to the same EventHandler. so that button click on all your Buttons will fire the same `Event Handler.
Step 2: You need to cast the object sender into Button and then access its Text property to get the Button Text.
Try This:
button1.Click += new System.EventHandler(MyButtonClick);
button2.Click += new System.EventHandler(MyButtonClick);
button3.Click += new System.EventHandler(MyButtonClick);
private void MyButtonClick(object sender, EventArgs e)
{
Button btnClick = (Button)sender ;
guess(btnClick.Text);
}
Cast sender to type button.
Example:
private void guess_Click(object sender, EventArgs e)
{
guess(((Button)sender).Text);
}
You need to cast the sender object to the Button type and use that:
private void guess_Click(object sender, EventArgs e)
{
Button senderBtn = senderBtn as Button;
if(senderBtn != null)
{
guess(senderBtn.Text);
}
}

How to connect text change event in multiple text boxes to a single method (C#)?

When I double click on my text boxes in the designed, it creates a method auto-magically for me. Since I wish the same things to occur in any of the cases, I simply call an auxiliary method from each, like in the code below.
private void TextBox_1_TextChanged(object sender, EventArgs e)
{
TextChanged();
}
private void TextBox_2_TextChanged(object sender, EventArgs e)
{
TextChanged();
}
private void TextChanged(object sender, EventArgs e) { ... }
Now I'd like to know if there's a way (other than going into my design file (which, according to the information in it, shouldn't be attempted to) to connect the actions listeners to the same method and skip the detour via the automatically generated ones.
On the designer page go to the events tab, find the event you are looking for (TextChanged) and manually enter the name of the event handler you wish them all to use.
I usually proceed like this in my projects, if controls are not going to change at runtime (i.e. if all controls in the form are added at design time):
// this is the container's ctor
public MyForm()
{
TextBox1.TextChanged += new EventHandler(UniqueHandler);
TextBox2.TextChanged += new EventHandler(UniqueHandler);
...
TextBoxN.TextChange += new EventHandler(UniqueHandler);
}
void UniqueHandler(object sender, EventArgs e)
{
TextBox source = (sender as TextBox);
// handle the event!
}
If controls will change, it's actually quite similar, it just doesn't happen in the ctor but on-site:
// anywhere in the code
TextBox addedAtRuntime = new TextBox();
addedAtRuntime.TextChanged += new EventHandler(UniqueHandler);
MyForm.Controls.Add(addedAtRuntime);
// code goes on, the new textbox will share the handler
In the properties fold-out (most often to the right of your screen) you should have a thunder icon. That's where all the events are referable.
If you don't see the properties, select the regarded component (the text box in your case), right-mouse it and pick "properties" in the context menu.
You can do it by this way:
void btn1_onchange(object sender, EventArgs e)
{
MessageBox.Show("Number One");
}
void btn1_onchange2(object sender, EventArgs e){
MessageBox.Show("Number Two");
}
public MyForm() {
Button btn1 = new Button();
btn1.Text = "Click Me";
this.Controls.Add(btn1);
btn1.TextChange += new EventHandler(btn1_onchange);
btn1.TextChange += new EventHandler(btn1_onchange2);
}
You could do it in designer view. Instead of double-clicking on an element - go to your buttons' properties, select events tab and then put a proper handler name for adequate event. Voila!
Follow these steps:
Go to the InitializeComponent().
There are three events attached to each text box.
There you shoud be able to see the following.
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged);
Replace this with
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
this.textBox2.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
And then remove the method below
private void TextBox_2_TextChanged(object sender, EventArgs e)
{
TextChanged();
}

button should refer to itself in C#

Assuming there are buttons with all the letters from the alphabet set as Text.
I want to call a function in these buttons and use this letter as argument.
Can I use the same piece of code for each button in some way?
something like
functionname(this.Text);
Problem is, that "this" referrs to the Form and not to the specific button.
In most event mechanisms you can obtain the source of the event; in classic win forms vents this is typically called "sender". You can cast the sender to what you know it is, or some common base-type. For example:
void SomeEventHandler(object sender, SomeEventArgs e) {
string text = ((Control)sender).Text;
// ...
}
Hence with this a single event-handler can handle all the buttons.
This may vary subtly between infrastructure / tools (WCF, XNA etc) but fundamentally should remain similar.
Try an event handler like this:
protected button1_click(sender as object, e as EventArgs) {
var button1 = (Button) sender;
if (button1.Text == "A") {
//for example
}
}
You will then need to add the event handler, either in "on load" using AddHandler... or if it's an Asp.net page you can use the onClick="button1_click" attribute.
For a more specific answer, I would need some more details.
You could use the same event handler for every button on the form:
private void Form_Load(object sender, System.EventArgs e)
{
foreach (var btn in this.Controls.OfType<Button>())
{
btn.Click += AllButtonClick;
}
}
private void AllButtonClick(Object sender, EventArgs e)
{
Button btn = (Button)sender;
String buttonText = btn.Text;
}

how to handle programmatically added button events? c#

I'm making a windows forms application using C#. I add buttons and other controls programmatically at run time. I'd like to know how to handle those buttons' click events?
Try the following
Button b1 = CreateMyButton();
b1.Click += new EventHandler(this.MyButtonHandler);
...
void MyButtonHandler(object sender, EventArgs e) {
...
}
Use this code to handle several buttons' click events:
private int counter=0;
private void CreateButton_Click(object sender, EventArgs e)
{
//Create new button.
Button button = new Button();
//Set name for a button to recognize it later.
button.Name = "Butt"+counter;
// you can added other attribute here.
button.Text = "New";
button.Location = new Point(70,70);
button.Size = new Size(100, 100);
// Increase counter for adding new button later.
counter++;
// add click event to the button.
button.Click += new EventHandler(NewButton_Click);
}
// In event method.
private void NewButton_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
for (int i = 0; i < counter; i++)
{
if (btn.Name == ("Butt" + i))
{
// When find specific button do what do you want.
//Then exit from loop by break.
break;
}
}
}
If you want to see what button was clicked then you can do the following once you create and assign the buttons. Considering that you create the button IDs manually:
protected void btn_click(object sender, EventArgs e) {
Button btn = (Button)sender // if you're sure that the sender is button,
// otherwise check if it is null
if(btn.ID == "blablabla")
// then do whatever you want
}
You can also check them from giving a command argument to each button.
Check out this example How to create 5 buttons and assign individual click events dynamically in C#
seems like this works, while adding a tag with each element of the array
Button button = sender as Button;
do you know of a better way?
In regards to your comment saying you'd like to know which button was clicked, you could set the .Tag attribute of a button to whatever kind of identifying string you want as it's created and use
private void MyButtonHandler(object sender, EventArgs e)
{
string buttonClicked = (sender as Button).Tag;
}

Categories

Resources