Set button handle in C# - 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
...
};

Related

How to properly assign events to dynamically created buttons in c# Winforms?

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)

How to give function to Button which is created programmatically

I want to create button programmatically and give a function to it.
Function: when I click on the button, remove/hide the button.
enter image description here
Declare your Function as an event:
protected void YourButtonClickEvent(object sender, EventArgs e)
{
// To hide your button
Button button = sender as Button;
button.visible = false;
// Your code
}
Declare your button and attach the event to it
Button button = new Button();
button.Click += new EventHandler(YourButtonClickEvent);

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;

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

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