The other day I received a query about using second forms in Visual Basic. I found a link to some examples and passed it along but it left me unsettled. The teacher in me did not find those examples explanatory enough. Sample code along is ok as far as it goes but often beginners need more. In fact I tend to prefer more myself. So I set out this morning to create an example. While I was creating an example for Visual Basic I decided to create an example for C# as well because, well, why not? What this example does is to instantiate a second form which is a simple implementation of an input box. The input box includes a textbox for data entry, a cancel box (I keep wanting to label this “never mind”) and a Done button. It looks like this:
Exciting right? I believe that examples for beginners should be very basic. I’ll use this form for both code examples. The textbox is called txtInput. The buttons are btnCancel and btnDone which should all be self-explanatory.
If you want to load your own custom form in .Net the first thing you have to do is to create that form. I do that from the Project menu option and selecting Add Windows Form. Since I want to return data I need to create a property. This property (of course you can create several if you want) will allow the calling program to get data from the form. In this case I am using a simple string property like this:
The C# version might look something like this:
Why do we have it display as a dialog box? That is to make sure that our main program don’t go off and keep doing things before we are done with the second form. Our code in C# might look like this BTW:
I hope the comments are detailed enough. That is more comments than I might put in a real program but I think having them here helps explain what is going on a little better. One last thing, if you find this example more useful than what ever else you may have found please think about linking to it so that more people can find it. Thanks.