This question already has an answer here:
- Add events to controls added dynamically 2 answers
I have made a button using
Button buttonOk = new Button();
along with other code, how can I detect if the created button has been clicked? And make it that if clicked the Form will close?
Create the
Button
and add it toForm.Controls
list to display it on your form:Create the button click method here:
You need an event handler which will fire when the button is clicked. Here is a quick way -
But it would be better to understand a bit more about buttons, events, etc.
If you use the visual studio UI to create a button and double click the button in design mode, this will create your event and hook it up for you. You can then go to the designer code (the default will be Form1.Designer.cs) where you will find the event:
You will also see a LOT of other information setup for the button, such as location, etc. - which will help you create one the way you want and will improve your understanding of creating UI elements. E.g. a default button gives this on my 2012 machine:
As for closing the Form, it is as easy as putting Close(); within your event handler:
if your button is inside your form class:
(might not be exactly
EventHandler
)and in your click method:
If you need to show a message box: