How do I programmatically wire up ToolStripButton events in C#? - c#

I'm programmatically adding ToolStripButton items to a context menu.
That part is easy.
this.tsmiDelete.DropDownItems.Add("The text on the item.");
However, I also need to wire up the events so that when the user clicks the item something actually happens!
How do I do this? The method that handles the click also needs to receive some sort of id or object that relates to the particular ToolStripButton that the user clicked.

Couldn't you just subscribe to the Click event? Something like this:
ToolStripButton btn = new ToolStripButton("The text on the item.");
this.tsmiDelete.DropDownItems.Add(btn);
btn.Click += new EventHandler(OnBtnClicked);
And OnBtnClicked would be declared like this:
private void OnBtnClicked(object sender, EventArgs e)
{
ToolStripButton btn = sender as ToolStripButton;
// handle the button click
}
The sender should be the ToolStripButton, so you can cast it and do whatever you need to do with it.

Thanks for your help with that Andy. My only problem now is that the AutoSize is not working on the ToolStripButtons that I'm adding! They're all too narrow.
It's rather odd because it was working earlier.
Update: There's definitely something wrong with AutoSize for programmatically created ToolStripButtons. However, I found a solution:
Create the ToolStripButton.
Create a label control and set the font properties to match your button.
Set the text of the label to match your button.
Set the label to AutoSize.
Read the width of the label and use that to set the width of the ToolStripButton.
It's hacky, but it works.

Related

How does groupbox.Controls[i] or panel.Controls[i] work?

I am new to C# and was wondering how groupbox.Controls[i] and/oror panel.Controls[i] works?
I have a panel with a bunch of buttons in it to represent a keyboard. I change the color of the keyboard button when the key is pressed.
However, when I do keyboardPanel.Controls[2].BackColor = Color.Red;, my spacebar becomes red.
My spacebar is button55 and at TabIndex 54. Why is it my spacebar that turns red?
The reason that yoor space-bar gets red is simple: keyboardPanel.Controls[2] is the space-bar. please pay attention that the buttons are not necessarily added to the keyboardPanel.Controls list in the order they are named. Meaning: keyboardPanel.Controls[1] is not necessarily button1 and also button55 is not necessarily keyboardPanel.Controls[55].
Now, If you want to extract buttons by name you should use this:
keyboardPanel.Controls.Find("Button55" , true);
where "button55" is the name of that control and true goes for the option to search all the children.
But I think there is a simpler way to change the color. Using the Sender:
private void button_Click(object sender, EventArgs e)
{
Control btn = sender as Control;
btn.BackColor = Color.Red;
}
and make this method as the event handler of all the buttons' click event.
EDIT:
If you really want to re-arrange the controls in the GroupBox you should visit the the designer. The simple way to get to the designer is to right-click on InitializeComponent() in the constructor method of your form and choose Go To Definition.
There you will find the order that controls are added. something like below:
this.groupBox1.Controls.Add(this.button2);
this.groupBox1.Controls.Add(this.button3);
this.groupBox1.Controls.Add(this.button1);
I my case Controls[0] is button2, Controls[1] is button3 and so on. You can re-arrange them like below:
this.groupBox1.Controls.Add(this.button1);
this.groupBox1.Controls.Add(this.button2);
this.groupBox1.Controls.Add(this.button3);

c# label text won't update on usercontrol after button click

I have a usercontrol that is loaded to a panel on Form1 in a winform application when a menu option is selected. The usercontrol has buttons that are used to fire the printer select dialog and allow the user to setup multiple printers for the application. Each button configures the settings property in the application to store a printer. Under each button there is a label that displays the name of the printer from the settings property.
I am using events to manage the button clicks from the usercontrol. Everything works great with the events storing the correct printer in the settings property. However, I want the label to display the selected printer immediately after I select it in the printer dialog. It won't display the change of printer until I navigate away from the usercontrol and back. Then it shows the correct printer name for each button.
I am able to write to the label text just fine. I've tried refreshing the label, invalidating and updating the label. Nothing seems to work. Only navigating away and back will display the printer names in the labels.
Here is one of my button click handlers on Form1:
private void btnTwoByHalf_Click(object sender, EventArgs e)
{
ucPrinterSetup prn = new ucPrinterSetup();
twoByHalf.PropName = "TwoByHalfPrn";
twoByHalf.SetPrinter(twoByHalf.PropName);
prn.lblTwoByHalf.Text = twoByHalf.Printer;
}
Here is my menu option click handler:
private void configurePrintersToolStripMenuItem_Click(object sender, EventArgs e)
{
ClearFrames();
ucPrinterSetup printerSetup = new ucPrinterSetup();
pnlMenu.Controls.Add(printerSetup);
printerSetup.btnTwoByHalfClick += new EventHandler(btnTwoByHalf_Click);
printerSetup.btnFourByOneClick += new EventHandler(btnFourByOne_Click);
printerSetup.btnFourByTwoFiveClick += new EventHandler(btnFourByTwoFive_Click);
printerSetup.btnMiscClick += new EventHandler(btnMisc_Click);
printerSetup.btnDefaultClick += new EventHandler(btnDefault_Click);
printerSetup.btnSecondaryClick += new EventHandler(btnSecondary_Click);
ucConfigurePrinters configurePrinters = new ucConfigurePrinters();
pnlFrame.Controls.Add(configurePrinters);
}
Here is my button click handler from ucPrinterSetup.cs:
private void btnTwoByHalf_Click(object sender, EventArgs e)
{
if (btnTwoByHalfClick != null)
btnTwoByHalfClick(sender, e);
}
Everything else works fine. It just doesn't update the label.text after I select the new printer until I navigate away from ucPrinterSetup and back.
Update 1:
My printers are being stored in the application settings through:
twoByHalf.PropName = "TwoByHalfPrn";
twoByHalf.SetPrinter(twoByHalf.PropName);
twoByHalf.PropName is the name that I've pre-entered in the settings property for the application.
I then set the label text to the name of the printer with:
prn.lblTwoByHalf.Text = twoByHalf.Printer;
In Application-Settings I have preset printer names as:
TwoByHalfPrn - string - User - (no value)
The main problem seems to be that you set the label on a control other than the one you are showing.
When your click event (btnTwoByHalf_Click) is called, you should use
the user control that is currently showing, but instead you create a new one with ucPrinterSetup prn = new ucPrinterSetup();
This is not the same control that is showing, but a completely new control, so when you change the label in prn you change the label in an invisible control, the original control remains unchanged.
I can see 4 ways of getting the original control:
1.
You can get it from the menu. If you only have one instance of this control type in you menu, you can use something like (no error handling in my code):
ucPrinterSetup prn = pnlMenu.Controls.OfType<ucPrinterSetup>().First();
twoByHalf.PropName = "TwoByHalfPrn";
twoByHalf.SetPrinter(twoByHalf.PropName);
prn.lblTwoByHalf.Text = twoByHalf.Printer;
Or, if you do have more than one you can assign different names to your controls and use something like pnlMenu.Controls.Find("YourControlNameGoesHere", false).First();
2.
You can get it from the sender property in your event. The sender is the button in the control, so assuming the button is sitting directly in the control, the button's parent will be the control:
ucPrinterSetup prn = (ucPrinterSetup)((Control)sender).Parent);
If the button is not sitting directly in the control (for example, it might sit in a panel that sits in a control) then you might need to up the chain more, you can put a breakpoint in the event entry and inspect the sender.
3.
The third way is maybe the best, but it requires you to change your design. It seems that you create the control again and again each time the menu is clicked. Maybe there's a good reason for it, but assuming there's no real reason for it, it's probably better to create the user control once when you start, and just switch the original control in and out. Then you can just put your control in a class variable and use it from your event.
4.
And for completeness you can also use a lambda/anonymous method for your event and capture the control when you register the event.
If you do that, then in the method which you register the event, replace the registration code to something like this:
printerSetup.btnTwoByHalfClick += (sender, e) => btnTwoByHalf_Click(printerSetup );
And then change your event method signature and code to be like this:
private void btnTwoByHalf_Click(ucPrinterSetup prn)
{
twoByHalf.PropName = "TwoByHalfPrn";
twoByHalf.SetPrinter(twoByHalf.PropName);
prn.lblTwoByHalf.Text = twoByHalf.Printer;
}
This might be the easiest code and less error prone to use, though notice that if you need to unregister the event later on, it might prove tricky.

How to make a button on/off switch?

Using VS2013, C#, .Net and Winforms how can I make a regular Button look "pressed"? Imagine this button is an on/off switch. ToolStripButton has the Checked property, but the regular Button does not.
Are you really forced to use a button or does it just have to look like one? For the latter you can just use a checkbox with the Appearance set to Button and Checked=true. This will make the checkbox appear like a button which is clicked.
If it is a custom requirement i.e. the button you need does not exist in the regular controls, I suggest you create a custom control button for your needs. Here is a link of a tutorial to create a custom control : How to: Create a Custom Image Button Control
You can also use a third party control like : Telerik Button - Radios and Checkboxes
Once the files are available to your site, activating the script is very easy:
...
$(document).ready(function() {
$(':checkbox').iphoneStyle();
});
You can change button's background image or background color in button click event handler.
Decalre somewhere in your code :
bool isClicked = false;
In event handler you can do :
private void button1_click(object sender, EventArgs e)
{
Button btn = sender as Button;
isClicked = !isClicked;
btn.BackgroundImage = isClicked? image1 : image2; // or use BackColor
}
There is a better and elegant solution. You can take a look how .NET draws it itself and try to do the same.
You should basically use
System.Windows.Forms.ButtonRenderer
class for drawing buttons in different states (Pressed, Hover etc.)
Please try to avoid using images for displaying states because to do it correctly, you would need to support different DPIs, sizing, proportions and so on. Rely on standard Render* classes fist.

Windows Forms - detecting button click from a panel inside the form

I have Windows Form named - Form1 and inside Form1 I have a panel named panel1. I use this panel only to add buttons in him. For now there are exactly 9 buttons but I intend to change their number dynamicly if this has something to do with my current problem. What I need is way to detect a when a button from this panel is clicked (I have other buttons too but, they are in Form1 outside the panel) and also to know exactly which button was clicked.
I tried this:
private void panel1_Click(object sender, EventArgs e)
{
MessageBox.Show("HI" + sender);
}
As you can see, it's not much, but was enough to see that I can't do that using pnael1's_click event. Using this code I get the message box when I click anywhere in the panel except the buttons. So how can I do that. Is it possible to do it from inside panel1 or I should group those buttons using another approach but it's important to be able to keep the difference between those buttons which are now in panel1 and the other buttons I may (and in in fact I do have)?
When creating the dynamic buttons, you register that button instance's Click event and attach to an event handler (a single handler can handle all buttons' click event):
var dynamicButton1 = new Button();
dynamicButton1.Click += MyButtonClickHandler;
As long as MyButtonClickHandler has a signature that's suitable for a Click event (that's any method returning void and taking an object and an EventArgs, the handler should respond to a dynamic button's click event for as long as the button instance exists.
As long as you aren't adding controls dynamically over time, and the number of buttons is fixed as soon as the form is initialized, you can use this to add a click event handler to all buttons within a panel:
foreach (var button in panel.Controls.OfType<Button>())
{
button.Click += HandleClick;
}

Dynamic Naming of C# Form Elements

My app needs to be able to dynamically create new form elements and work with them. Right now I have a panel with buttons and labels in it. I need to be able to make a duplicate of this and show it in my app and then work with it.
For example, I have panel1. Inside are label1, button1, and button2.
Label 1 just counts up by seconds.
When you click button1, label1 starts counting up. When you click button2, the timer stops.
My problem is that I need to be able to duplicate panel1 many times and still have the new buttons correspond to the correct labels.
On button_click
private void button1_Click(object sender, EventArgs e)
{
Button theSender = (Button)sender;
Panel parentPanel = (Panel)theSender.Parent;
}
From here, I can't target any of the child control . I'm used to targeting and handles in jQuery, so I don't even know the correct C# terminology for how to explain myself.
If understand your problem correctly, I recommend you to make a Usercontrol with a Panel and fill it with your Label, Button and whatever. Write the events for your buttons in the usercontrol. Then introduce this usercontrol in your form and it should work. You can introduce any number of usercontrols in your form and each button will behave/work for the label in that usercontrol only.
As you mentioned you are new in winforms and you are not sure what I am saying, let me know and I will help if I get enough time.
Hope it helps.
Children of a control can be accessed using Control.Contrtols collection, e.g. to access button on a form:
Button btn = this.Controls["button1"];
But that is only true if button1 is placed directly on your form and button1.Name property is set to "button1" (designer does that automattically, if you are creating your controls dynamically, you have to take care of naming your controls yourself.)
You can also enumerate child controls of any control, e.g. child controls of panel1:
foreach(Control c in panel1.Controls)
{
// do something, e.g.
if(c is Label){//do sth...}
if(c.Name.Equals("label1") && c is Label)
{
Label l = c as Label;
}
}
and as #rapsalands said, UserControl may be an answer for you.
I would create a user control (UserControl) for this.
Check this article for more explanation about the difference between Control and UserControl.
Controls and UserControls are easy to duplicate and the full functionality is there.
You can create new UI Controls in code as you would any other object: Button b = new Button();
Then you can add them to the form using form.Controls.Add(b). You'll need to position and size the controls as well (there are properties available for doing this) and hook up your event handlers using b.Clicked += form.button_click;.
To see an example of this, you can try having a look at the designer.cs file that is generated in Visual Studio (don't make changes to it, just have a look). It will look quite complex at first but might go some way to helping demystify Windows Forms, and you will be able to find all of the properties you need to set in there.
Whenever you update something in the designer, Visual Studio generates new code and puts it in the designer.cs file. The entire form is set up in the InitializeComponent() method, which is called from the constructor of your form. You should be able to copy some of that code and with a couple of modifications use it for creating your own dynamic UI elements.
As rapsalands says, it sounds like a user control would be useful in this situation, as it will help encapsulate the functionality you're after. However that may take a bit of time to get your head round and you may find it simpler for now to do everything in your form without creating a new control.
So you are a beginner and need some time to understand Usercontrol as I mentioned in my previous answer. Use a for loop in the Constructor or Load event of your form to dynamically generate controls.
Panel panel;
Label label;
Button button1;
Button button2;
for(int i = 0; i > count; i++)
{
panel = new Panel();
button1 = new Button();
button2 = new Button();
label = new Label();
panel.Controls.Add(button1);
panel.Controls.Add(button2);
panel.Controls.Add(label);
Controls.Add(panel);
button1.Click += Event1;
button2.Click += Event2;
}
private void Event1()
{
label.Text = "Button 1 Clicked."
}
private void Event2()
{
label.Text = "Button 2 Clicked."
}
This way certainly you can create as many controls you want and will also serve your purpose. Use some variables to locate the panel controls appropriately. Set any properties you wish to add in the for loop for the controls.
This is just an alternative for my previous answer. I still recommend the previous answer given by me. This code is dummy and not tested.
Hope it helps.

Categories

Resources