Intro to Windows Forms (WinForms) in .NET 6

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
windows forms also known as winforms is one of the original project types in.net it is designed to be a rapid application development environment for desktop applications over the past 20 years other desktop application types such as wpf uwp and now.net maui have come along so when will we use winforms in this video i'm going to show you what winforms is how to build it what the best practices are how to avoid some common pitfalls and when you should use the winforms project type this product type still has value even though we have other shinier tools in our toolbox now if you don't know me my name is tim corey and it's my goal to make learning c-sharp easier i do that by providing videos here on youtube multiple times per week plus i have a weekly podcast i also provide courses on c-sharp web development and much more at iamtimcorey.com the profits from those sales are what pays the free content here on youtube so that everyone can have a great education in c sharp not just those who can afford it in this video as with most of my videos i'm going to create some source code if you'd like a copy of the source code use the link in the description all right here's visual studio we're going to create a new project and today we're going to use the the.net 6 version of winforms because there is a little bit of a difference here so if we choose the i'm sorry the desktop project type over here for filter we'll see windows form app now i also have windows form app for net framework but we're going to choose this one right here windows form app which is the net core version that's going to ask me which version in just a minute we're going to call this the winforms demo and winform demo app and we're going to say net 6. so there is just so you know a bit of a dividing line between net framework and net core it wasn't just the fact that yes we upgraded the backend c sharp code language and what builds upon to be.net core there was also a replacement of the windows form designer so there is a different designer for this than there is for the.net framework version now you probably won't be able to tell visually but it is different let's hit create so the difference here is they had to kind of rewrite things in order to work with net core so when you work with it you might find a glitch or two even though they pretty much worked out most the bugs but that's because it is a totally new designer as compared to the original designer that had been around for well over a decade almost two decades so this is what you get with windows forms out of the box when you first start up you already have a design surface you can work with that has the minimize the maximize and the close buttons you have a little name up top form one a little icon and you can actually just run this and let's just do that right now to see that with just a bare template we already have what could be considered a working app you can resize it you can maximize it you can restore it you can minimize it you can close with the x button now of course that doesn't have it in your code doesn't actually do anything but that is the the foundation of a windows form app i'm going to kind of walk through why we use this project type well i mentioned earlier that this is a rapid application development environment it's designed to be able to get you out the door quickly with a project now this can be taken too far this can be taken into extremes that really cause um you get your application out the door fast but then have long-term problems we don't want that so let's talk through what is rapid application development well let's say you have an idea for an application you want to do a a test of it to verify that hey you know let's just see if this even works well it's very easy to create a proof of concept using windows forms you see this toolbox over here has a whole bunch of controls and let's just pretend we're going to start off and really make a mess of things and that's okay we're going to see how to fix those but you start dragging on you see oh i'm on a button and i'm going to make this a little bigger or here's a button and we're going to have a let's go with a text box we're going to grab a couple of those so i'll put one there we'll create a label for that too and so we'll put that there and kind of line it up and then we'll just do a well i hit control that way select one hit control and hit the other one and i can control c and control v to copy paste notice that the nice lines that line this up and before you know it i have what looks like a pretty decent form set up and i can actually do things with this and that was pretty quick i have what is or could be a working application so i now have forms i can you know type it i hit tab go to the next field and so on hit tab again the button is right there now it doesn't do anything but it could it might say well let's you know up the complexity a little bit and put a little checkbox in here line that up and so on so you can you can really um do a lot of stuff just by dragging and dropping there's a progress bar which right now is is empty but if we went to properties over here um i believe the it's the value let's just put the value of 45 and there you go there's a progress bar at 45 out of 100. so there is your really rapid proof of concept and this could be used for design only if you want you can just say hey let's just look and see if this works as far as a visual design but then you could even start wiring things up a little bit and say well if you double click on the button it creates an event so i double click the button and it creates an event and it puts us let's unpin all of this it puts us into the code and it says private void button one click so when the button one is clicked this is what's gonna happen this code right here and i could say well you know what let's do a um message box dot show and we're going to put a message in here so we'll put a string interpolation and i'll put it semicolon at the end and i'm going to grab the values from this first text box in the second text box so i could say hello and then the first text box is probably called text box 1 yep and say dot text and then space text box to dot text so what we're doing is pretending here the first text box has a first name the second text box is a last name and so a text box is an object we're going to talk about these obviously a minute but it's an object on the form and if we go to properties here we'll see that it's called text box one or up here's a name text box one so you can tell that's text box one and this one is text box two i'm assuming yep so by doing this we can grab the values out of it so this right here we can grab a text which is the the actual text inside this box and so with just those little tweaks of code i can put you know tim corey and i can come down here hit the button and it says hello tim corey so we've got what could be considered a working application and if you've ever taken a c-sharp course in college or somewhere else that's probably the first demo you ever saw is something like this where you just drag and drop some stuff on me some rename some stuff like label one to be first name but you build this application you think cool i'm a developer which you are you have written applications you have written code so don't let me tell you're not a developer but you're not a very good developer yet you've got some you got some ways to go and really i don't like teaching windows forms as the first place to learn c sharp so if you are brand new to c sharp this is not the place to start this is you know it's intro to this is not the place to start to learn c sharp because there's a lot going on behind scenes that we're going to talk about and if you are not familiar with object-oriented programming this is going to be a bit complex and it's going to be a whole lot of magic because right now you've seen magic and i'm not a big fan of you just saying well it's magic because magic breaks things happen in fact before you go on i'm going to show you one of the most common problems that people have in windows forms i used to teach at a college and i taught c-sharp and there was other professors that also taught the intro c-sharp course and so i would get students from other classes that would come to me trying to take the course again and one of the things i would ask them is what did you do when the designer broke and the answer was i would start over so i'm going to show you what happens when the designer breaks so let's let's say we're working on here we accidentally double click the form itself and go oh that's not what i wanted to do let's go ahead and get rid of that cobia that's that's not i didn't want to do that cool okay we're going to save that come back over here and what will happen is actually it's not breaking right now which is awesome maybe i've changed this but let's open it back up hey there we go um the form broke so when i try to open the form up i can't like normally you double click this form one it opens up and it says the designer cannot process unknown name form one underscore load at line 153. so you're like no no let's try this again nope still didn't work so you restart visual studio because maybe it's a stupid visual studio bug it's not a visual studio bug so they the the answer a lot of new developers come up with is i have to delete my projects and start over because they don't know how to fix this the magic broke because the magic was just the form designer just works right well no there's actually code that that powers it that we can modify that we have access to so what's the problem here well when i was in the code i deleted some code here let's see if i can control z i can't control z because that's already closed uh i deleted some some code here that said form one click i believe um that was an event handler like this is so i i didn't need it though so i deleted it but for some reason now my form designer doesn't work well those two things are i wasn't click it was load those two things are related but maybe you didn't realize it maybe you did you did multiple things like you saw me it even seem to still work on the designer but then you close out and restart and doesn't work well the issue is i deleted the handler in one spot but not the other this is where understanding how windows forms works really helps also reading error messages really helps the error messages in visual studio used to be now i'm old school developer i have worked with with microsoft error messages for 25 almost 30 years so i've seen a lot of bad error messages and they used to be horrible it used to say an error has occurred and that was about all the information you had but now we have really good error messages a lot of the time and often people just skip over and say i don't know what's happening well guess what you can read this and it will tell you what's happening and tell you where to go so it says the designer cannot process unknown name form underscore load at line 153 the code within the method initialized component is generated by the designer and should not be manually modified please remove any changes and try opening the designer again and it says go to code there's a button right here click it and it takes you right here a line wait it says 153 it's actually 154. this line right here notice the red squigglies but how do we get here well a windows form is actually a has a split class behind it so if we right click on windows winform.cs and say view code we get this code which we've seen but notice it says public partial class and what this allows us to do is it allows us to put two different files or two different places to put form one class code and the benefit here is mostly just for these type of environments usually don't use this in our own personal development but with a generated form microsoft generates code for wind forms and so it says hey we don't want you messing around with this generated code so we're going to put that generated code in one partial class and then we're going to give you the rest of the code the code you can modify freely in the other partial class and then when the compiler goes to compile our application it takes those two partial classes and puts them together as one file so it's just a convenience for us so we don't see all the generated code in here but where is that generated code well it's in form1.designer.cs so you don't click on this this is if you expand out form1.cs you'll see it right here so it's designer.cs this is code that you should almost never modify i see almost never because we're going to modify it let's open it up and this right here is generated code okay this is code generated by by the designer required method for designer support do not modify the contents of this method with the code editor it's saying don't make changes here now that's a pretty strong warning and yeah you probably in in 99 cases out of 100 you should not modify this however there are times when it is the right call to make a modification here so let's go down and look notice this dot button one equals new button new text box new label new label new text box that looks familiar new progress bar new checkbox that is a code representation of the items on our form we'll get back to that in just a minute we have here configuration button one it says this is great it's great how they um put all the stuff together and really documented it either let's modify it but it says location name size tab index text visual style back color and the click event this is all the stuff related to that button but then we come down here to the line 154 i believe and we see that this is the form 1 section and we see controls dot add progress bar checkbox and all the rest but then down here we see load plus equals this is an event so the load is an event handler and we're associating we're social i'm sorry the low is an event and we're associating event handlers with it so we're associating a new event handler for the form load and this was in the other half of this class notice i didn't even show you up here this is partial class form one over here we had public partial class form one those two connect those are the two things going to be added together but down here on line 154 we say new event handler and say this which just means this class for this object and say form 1 dot underscore load which we put that code over here in this half of the partial class just like button one underscore click but it's not here because it's not here it's having it has an error because it doesn't exist the solution is to get rid of this line that will take away that handler now i am modifying the automatically generated code that's okay in this particular case if i hit save go back to the designer we can now see the form so what happened that caused the problem then what did we do to fix it well when we double click anywhere it creates the default event and while i say default event well if we click on the button which we already know has an event if we double click on it it goes this event button one r square click or the event handler the actual method to handle the event but there's more events we could do we have properties let's pin this from it well let's not let's go to events so up here let's zoom in this is the properties window but the properties window not only has the properties of our button but it also has this little lightning bolt here which is events and these are all the potential events for our button let's kind of zoom back out and look at all of these it even on my screen it only goes through e on all the events we could do and we can scroll down through so for instance we could have an event on mouse hover or mouse click because we have on click right now which would be any type of click so it would be if you tap it with your finger if you click the mouse click if you tab over and hit the space bar those are all click events but we could have on just mouse click we could say hey you know what when it's the visibility has changed do something which doesn't happen very often um we could have it be when you drag and drop something onto it there's a lot of different things you could do on the event but the standard one is for a button is click so by default when you want to create an event you probably create it on click not on there's a double click in here um but you can have on different things you know right click and all the rest but it's probably under um miles click or um i thought there was a double click anyways not a big deal um but what you can do is modif you can monitor different events but for this case there's only one that we usually use and so microsoft says hey that's the default one so if you double click on this i'm going to create that event when we create click on the form itself well we don't normally track what a person clicks on the form that would probably be annoying but there are other events on the form so this is the form one and one of them is load right down here occurs whenever the user loads the form so sometimes you want to do something when the form loads maybe it's uh put up a splash screen or maybe it's uh put the cursor in the right spot or maybe it is to start a timer that does something after a certain number of seconds there's a lot of things you could do on the load that's probably the most common event that we do we monitor for the form so we double clicked on the form the designer says hey a double click means creating the default event for this item and so it created the load event but then when we went over here we said oh i don't actually want that event handler which that little bit of code like this we delete it but we didn't delete the actual event handler wiring it up we just deleted the code for the event handler well then the windows form couldn't generate the actual display for the form and so it says i don't like to do i'm going to break which brings us to an important point what we see here the actual visual design of our form is just code being rendered in the designer that's all it is so we look over here let me see all this code this code is responsible for what this layout looks like so when we mess something up where it kind of breaks that code it can't render this form because this form doesn't doesn't just exist it has to be created it's essentially running our windows form ui in the designer now it's not the exact same because it's just displaying it's not actually responding to events and other things but that's kind of what i was doing and so we mess up the code it messes up the ability to render this which means it can't even show us the designer because the designer isn't just magic it actually has to be built off of logic and if that logic is broken the designer is broken so let's talk about what windows forms is windows forms is really a class that's all it is so there's a special class called the form class which we inherit from notice the inheritance right here so we're inheriting from form which brings a whole lot of methods and events and other things with it and then we just add other classes to it so this is our the designer so here's our partial class form one and notice on the initialize component we've got this dot button one equals look at this equals new system.windows.forms.button that's a class textbox is a class label is a class checkbox is a class progress bar is a class we're just adding class objects to variables inside of our class our form 1 class so what we're doing here is just creating a pre-complex class with a whole bunch of properties and methods inside of it and it just happens that we can then use that to render a visual like this so all of this happens because we inherit from form which has figured out how to render this stuff on the page form is what gives us the outline the gray background the minimize maximize and close buttons the ability to resize the window the ability to render the button and all the rest things the way we expect them to so that's all based upon inheritance and it's all based upon bringing all that those libraries from microsoft into our form we're building on the shoulders of giants they microsoft has done a lot of work just to give us this shell when i was uh playing around with c plus plus early early on this is decades ago i was playing a c plus plus and and trying to build a a windows form basically a form for a screen but from scratch just code and i wrote dozens and dozens of lines of code to build out from scratch this this form that would be on my display and i was just getting started and so i got to a point where i said i think this is what would actually render my my page render my my view my form and so i ran the application and it didn't seem to work until i tried to click anywhere on the screen and i realized that i had created a transparent window that was across the entire window that had no minimize button had no close button it had no ability to give me a right-click menu it was just a big transparent window and so the way i solved that was to restart my application restart my i'm sorry my whole computer in order to restart my application because i couldn't get out of it because i needed to code the minimize button i needed to code the ability to have a background i need to code the right click menu i need to code all that stuff and i hadn't yet well with windows forms microsoft says you know what you're going to be creating these minimize maximize and close buttons all the time why don't we do it for you and we're you need to have this title bar and the title and the icon and the resizability every time so why don't we create it for you and this is how we don't repeat ourselves this is dry because microsoft said we'll do all that work inside of form this is where inheritance is really valuable in c sharp because we can inherit all of that pre-done work for us in a way that makes sense it's not just code sharing it's actually makes sense that we create a base form that we then inherit from and if you actually hit you can there's rabbit trail it's quite a rabbit trail but hit f12 in form and it's going to take you to the namespace system.windows.forms and it's the class form we're inheriting from and notice all the stuff that it adds to the class but then notice that at the top it actually inherits from container control well if you have 12 here container control adds a whole bunch of stuff knows about 370 lines of code that's just the actual definitions the not actually code itself that's more than that but then inherits from scrollable control and it implements the eye container control let's go scroll control f12 and that adds a whole bunch of stuff but then that inherits from control also notice all the interfaces here but control hit f12 and that brings in a whole bunch of stuff and you can go down this rabbit hole all the way through component and so on but that's all the stuff that we're bringing in that's what kind of they have invented the wheel they have invented the engine they have invented the doors and the all the other things for a car and said okay here's all the parts and you can just kind of customize it the way you want and you can inherit from form that's how windows forms works so windows forms you already have baked in a whole bunch of things so if you look at this kind of from a new light here this is a class that's just getting rendered and when we dragged on a text box what we were doing is saying i want to add a new variable to my class that's of type textbox which is a class and we instantiated that class so we go over here to properties this kind of makes more sense now and let's um let's drag this out and put it separately there we go um and we're going back to properties notice the lightning bolt and right next to it is the the wrench and the page thing that's the properties but notice all these properties if you come from an object-oriented background if you know what object oriented is in c-sharp then the word property should kind of flag something in your brain because when we look at classes forget about windows forms when you create a class itself you create properties and methods by default those are the things that you generally create in a class they can also create events well these properties right here are our properties they're properties like in the class it's just that we have a designer that shows us what those properties are but these are available as just properties and we can modify the value of that property by changing things so let's go over to label that makes a little more sense so it says the property called text is label one well i can change this to say first name if i click off it notice over here it says first name cool so now i can see the the value of this because i can i can have it visually match up what i'm really doing is modifying the value of a property that will then be set for at least the start of our application kind of the default value for our property because we can have the code change it and that's another thing is now we're understanding what properties are if you come over here this makes a little bit more sense because i said i want a message box let's we'll forget where this isn't for a minute but i want a message box that said hello tim corey so i did the string interpolation i said hello and i said text box 1 which is a class and i said give me the value of text which is a property on that class and that's a string property notice i hover over it it's a has a git or a setter and it returns a string value so this is the property that i wanted to access from text box one but i could make more change i can work with the properties as well so i could say text box 3 which is the one right below first and last name i can say dot text but instead of reading that value i could say equals and then let's grab this whole thing we'll take the hello off so it's just first name space last name so i'm modifying the value of a property of an object or a class instance on my form so now if i run this i can say let's mod for the first value tim last nam value it's corey leave the other two alone hit button it says hello tim corey and then it now says tim corey and label three so the reason why is we have to modify the properties of pretty much anything i could say you know what i don't like the fact that they say um text box ones i'm sorry the label one or label two says label two and label three says label three so let's do this let's on the constructor i'm going to say label 2 dot text equals last name and label 3.text equals full name i can run this and notice it says last name and full name now is this the best place to do this probably not because probably it's better to see it in the designer and it's probably we don't need to write code for this when we can just have it done as a default so but i want to show you that as possible it's possible to do this where it says lasting and full name even though it says label two and label three here in the designer because i've made a change at runtime i can also change this value as well so let's just say that every time you click the button we're gonna show the message we're gonna display we're gonna change the the full name um and actually you know what let's comment this out let's not bother with with that display instead we're just going to say progress bar 1 dots because value yep value plus equals 10. okay so now i hit the button notice it goes up and it goes up and so on now i believe i get past here yep i can't do that 105 is not a valid value because there's a minimum and a maximum and i see the maximum but that shows you that you can make modifications to properties of your objects because these are just objects which take a step back what is form one it's an object it's an instance of an object which means that i could also comment this out and i could say form one and call it frm equals new form one what is this doing it's creating a new instance of form one and then i could say for frm dot show which is a method where that method come from it came from the inheritance from form so what this does is it shows this particular instance of form one so if i were to run this now i click the button it actually opens up a second window click that button it opens up a third window and so if i see the first window tim corey notice does not modify the second one or the third one because these are different instances of the form each one is separate a separate class instance so form one is a class and we instantiate it when we run which is how we can create multiple windows very easily and this is why this is called rapid application development because we can drag and drop stuff on here very quickly and make things work but we really need to take a step back and understand what's happening here if we want to use this for anything more than just demos or prototypes now i do want to say that i have mentioned prototypes more than once and there is a word of caution here i personally don't create working prototypes very often in fact almost never do i create a working prototype instead i would draw it out on paper and then i would make my customer the the um the owner of the project i'd make them walk through manually by touching the page there'd be a you know there'd be a button on the page but it's a written page and they'd you know push that and i'd say okay flip flip flip flip it there's where that goes and this is what happens and kind of give them the narrative but outside of the digital form and the reason why is because if you show us to a customer and it's working and it's a pretty cool demo that you know kind of does what you think it should do and they say yes can i have this tomorrow or can you give us me today and you're like no this is a prototype it doesn't actually do everything it's not really the full application they say no no it's already working why would it take you another three months to get this done because if it looks too much like it's real then people think it is real so be careful on that but if you're testing something out while try something want to have an initial version you can you can do this you can create something that um is pretty easy to just kind of bang out in a couple of days or even a couple of hours but let's talk through um you know what else is going on here because it's important to really understand windows forms if you're going to work with them so with windows forms we have this form1.cs that we get right out of the box now i have not done any modifications to this project i kind of let it be right out of the box i'm going to show you a new project in a little bit where we can't do some initial modifications that i recommend in order to make this a better project but let's look at the other parts of the project first so how does this work like we hit the run button it just launches that form how does it know which form to launch in fact if we right click on here and say add new form and let's call it because this is the um don't do it this way demo i'm going to leave it as form2.cs um so form two there you go and let's just drag on here a oh i don't know a uh a label and we're gonna come in here go to properties and in properties i'm going to say form two and we're gonna make this really big let's go to the font and we'll change this font to be 26. okay better and we'll kind of center this so this is our form two but oops i close out property that's okay you can go to uh view and because i have such a large font on my screen if i scroll down the properties window right down here f4 there's back i can unpin that that's what i want to do but if i have form 1 and form 2 and i launch the demo this is what launches form 1. so how would i get to form 2 well i could put in the button on form one wait for it it's uh having problems rendering this form one let's close all this this is the quirky stuff that happens in this application sometimes uh because it is a new form designer they had to rewrite the entire thing because of net core but we don't click on button go back to this event we can change this to be form two so form two i can just do this equals new so that's a form 2 is going to show so if i run this it's sorry i open the first window i hit button 1 there's form 2. okay that's kind of cool but what if i wanted form two to the one that started off the bat initially well that's where you have to understand how this application actually gets launched which is from program.cs i'll open that and you'll see that there is this static void main and inside of here we'll see we initialize the application configuration and then we say application dot run new form one that's how we're launching our initial form now that's also important if we run this again click the button so we have form 2 open let's close form 1. okay close the entire application even though form two is open and that's because what happens here is this initial form that gets run is considered the main form and so that form will be the lifespan of the application when that form closes the application closes so that's going to think through there are ways around that but that's how a windows form application runs is when the the first form you launch closes the application closes too so that's what i think through but if we change this here to form two instead of form one and run this this we get form two that's what launches because that's the starting point of our application now in our application doesn't make a whole lot of sense because form one really was like the main form the the form that had all the good stuff and the way to open form two and all the rest but that's where it is that's how you modify the starting point of your applications right here application.run and which form is it so that's that's the basics of our application now let's look real quick at come back to form one wait for the designer to load let's move the toolbox real quick because this is a really big deal these are notice the common controls when it opened up and we have button checkbox check list box combo box date time picker notify icon number up down tool tip text box and so on these are the common things that we're used to these are all common controls here on this page but we really have a lot more for example containers um container we can do group box we can do a tab control so you have multiple tabs on this form and you click on a different tab it goes to let's say a different form but it's just a different part of the tab form we can have menus and toolbars this is kind of cool we can we can actually bring on one of the ones is the status strip so drag and drop is on notice down here is a little status strip and it allows us to say okay let's put a progress bar here and let's put a a status label now these these names be horrible so let's look at let's pin this here and unpin this let's look at you know this this one right here is called tool strip status label one and this one is called uh tool strip progress bar one but with this we could come over to our button and we could comment this out again we're always commenting this out and unpin this we can say that tool strip progress bar 1 dot value plus equals five and then we could say that the tool strip progress bar or tool strip status label1 dots text equals working dot dot so if we run this application now it looks like the the window notice in visual studio we even have windows like this down here um but it's a little window down here that or strip that gives us information about what's going on so you click the button now this is working we got a little progress bar i could see it load up and we could actually do this on a timer and we got to the you know 100 it could say ready and then hide this this progress bar or something like that so we're very familiar with this we we have this down here as red strip in visual studio is something similar so if we're compiling something that will you know show us compiling if we downloaded something that would show us downloading so that's one thing we can do we can also add a menu strip here just drag and drop it um pretty much anywhere notice down here in the very bottom this is we can modify these items but we can start saying things like okay i want to say file and i want under the file menu i want i believe the file menu um if we do the alt it's f and then exit is under the x so it's been a while since i've done this whoops i double clicked and again i created this event how do i get rid of that event great time to talk with us well i can come back don't delete it here i can come back to the designer i can click on the file i can go to properties go to events notice i just click event highlight it and delete it from here now come back over here that code is usually gone but even if it's not i can delete it because it's no longer wired up to this file so go back over to properties and go back to properties themselves and i believe is it i think it's the ampersand like so yes cool okay i haven't lost my josh so e ampersand x i t enter and notice that it didn't put the ampersand in but instead what it did let's zoom in here it's super tiny there's an underscore under f there's an underscore under x and the reason why is because this is for accessibility so if we were to run this application right now now the these things don't do anything yet like it doesn't actually exit yet but if i hit my alt key notice it highlights the file but also it's underscore and f if i hit f that opens up the file menu and if i already hit x it would run the exit command because this is our alt menu now if i'm in visual studio that's why i just did to make sure that this is the common ones i hit my alt key and notice how there's underscores under every word and they're not always the first letter for example format the underscores under the o but if i wanted to open the view menu i could hit v and then notice underscores under everything so for example the output is underscore on the o and toolbox is underscore under the x and task list is the k and so on so with that i can without using my mouse go up to the menu and choose something so if i were to hit alt f and then hit x i'm not going to do it but that would close out visual studio that's a standard thing to do so it's a standard underscore selection i'm not sure you can call it but where we chose to say that f opens the file menu and x is exit that's what windows does so if you're building a windows form application you should try to follow steam standards whenever there's standard things so the file with the exit windows the help or window help about these things are pretty standard in your menu and you could create these things in your menu so you might say help and then have an about menu i'm just typing here by the way but these are now basically buttons and so in this but i can actually even have sub things under it but with about you wouldn't but when you're creating them you want to use the ampersand to indicate the space i'm sorry the the underscore so if i click on the help i believe um help is h and then the about is a so for help i come down here in the properties to help and put the ampersand in front of h and then for about i put the ampersand from a so now when i hit the alt key and then type h a i'll get the about menu which let's actually create something for the about menus and double click on about and this creates a click event on this tool strip menu item now we're going to talk in the next section about naming because this is really important and this is super ugly so i know that a lot of you hopefully are freaking out over my naming and that's a good thing freak out over it because we should not be naming things this way we'll get there we're going to talk about this in a little bit we talk about the best practices for windows forms but for now i was using the default names so this is the click event for that menu item now we're going to say message box which is just that little pop-up box that um is pretty standard windows forms but um yeah it comes kind of baked in it's the simplest way to show data so we're just going to say created by tim that's our entire about menu but if we run this now and i were to say alt h a it says created by tim i can do all this without my keep my mouse my mouse sorry i can do with just my keyboard not my mouse which can be very helpful for accessibility it's also a common way to interact with this this form so that if you have an application that's interacting the form instead of you know a keyboard even you could still enable these menus to be navigated now let's just show you really quick what you do for exit so double-click on exit there we go i would say i believe it's this dot close this is indicates this particular instance and close what you're going to do with it let's run make sure so alt f x and it closes out now we could do it manually click on it exit works too but it just gives you more options when you have that ampersand the the key is that you can't have two things in the same menu that have the same letter so if you have more than 26 things in your list that's a problem but that's already a problem anyways because that's pretty intense visual studio is pretty intense and it has 6 9 12 14. so the idea of having 26 or more it's pretty intense maybe you have some sub menus there but because no sub menus can have a repeat letter because now under that menu is the only context available there so that is that is the basics here there's a lot of stuff in here you know printing and data and components and so on that you can do dialog boxes and so on but let's talk now about first of all when would you use winforms then we'll get into the best practices for building a winform application so when would you use wind farms like i said rapid application development is really great for prototyping the idea that you want to create a quick proof of concept that says hey does this even work and you try it out with a quick and dirty form that just gets the job done that's super helpful sometimes again be careful that people don't think that it's the real thing so you gotta be careful who you show that off to but the other thing is if you just need a little application to do something why are you messing around with complexities so with wpf uwp dot net maui they'll use what's called xaml xaml and that's a designer language that can be somewhat complex now we didn't see any complexity here we just dragged and dropped things on the form so it's very quick to create a little application and if you need just something created that just works that doesn't take you a lot of time to build this is a great option so this can be used in production in fact this is probably the most common project type in production today you may say tim i don't believe you because you know the this is desktop only as windows only the world runs on the web and i'm sure there's more web projects for c-sharp i'm not so sure there are and here's why because this project type came out with dot-net one not.net core one dot net one back in 2001 2002 when dot net first came out and this was visually similar and how it worked is very very similar to what i used back in visual basic six and before so i think visualizing three i use a drag and drop editor like this so this has been around this design of style had been around for years so when dot net first came out and companies started adopting.net and becoming they kind of went to the bleeding edge of new technology they adopted.net they were comfortable with this windows form drag and drop and so we had for desktop applications we didn't have wpf yet so when they they decided to build their applications they built it in windows forms but then they still have those applications around today a lot of those companies and this kept building on them so those applications are still around they're still existing and they're still running and so it comes to you know manufacturing environments and uh office bus you know businesses that work in offices and so on business that create their own applications there are a lot of windows form applications out there microsoft has repeatedly tried to make new desktop application types and has fallen down over and over again trying to get them to become adopted as the primary desktop type first it was wpf and that was much more complicated compared to windows forms because it didn't just drag and drop now you can but that wasn't the strength of it or how it really flourished and benefited so it was more complex which meant it wasn't a rapid application development tool anymore it was just a development tool now so people still kind of fell back to well this is easier it's like stuck with windows forms and then they came out with uwp and microsoft said this is the future and it's tied into only the latest edition of windows and like people said yeah but i'm still supporting older versions of windows so i'm not going to do that and in fact now uwp has been deprecated it's actually died off and windows form is still around kika and still a pretty popular uh form type or desktop type and then you know net my way now people are saying well this is going to replace everything yes but maybe i'm not convinced that yet but even if it did even if dot net maui is everything everyone wants and is the best desktop and mobile application type there is if all that's true it's starting from today windows forms has a 20-year head start you may say well tim the web's been around forever and the web is the way to go well again no because the web has not been the way to go when it comes to building business applications for very long and by very long i mean maybe the past 10 years has always been but windows forms has been around for over twice that and again before that it was something similar that people were familiar with so when they switched over to net they used what they were familiar with so therefore there's a lot of companies out there still using windows forms now if you were to build a new application today would i recommend windows forms probably not i would probably recommend wpf if you want a desktop application maybe if you really thought you needed to i maybe i'd recommend.net maui but it's still pretty early in the in the game for that wpf is tried and tripped now you may twitch at that but there's a lot of good reasons for that we can get into that in a different video but with windows forms i probably wouldn't recommend it for a new application for a lot of reasons but there are a few that i would recommend it in first of all it is a great rapid application development tool so if you need something quick windows form is the way to go also it's simple so if you're a one-person shop and you have to develop a big application well the simpler it is the easier it is to maintain therefore yeah windows forms is a great option so there are a few cases when windows forms make sense for new applications but even if it doesn't make sense for most new applications it still has a place and it is one of the most common prototypes you'll see when you work in business so when you work on a company you're gonna see us you're likely to see this in a.net shop you're likely to see windows forms at some point even if they're trying to switch over to web even if they're trying to switch over to a later version you'll probably see some applications still running in windows forms because it's just so easy in fact if you're creating little tools to help you out guess what you're going to use probably windows forms this is the tool to use when you want to create a little tool for yourself or utility that just works and it's pretty quick so that's when to use it let's talk best practices and and how to use it well now first of all i want to point off point out that when i resize this notice how it kind of cuts things off these things don't move around this is why i say that wpf is probably the right choice for new applications because by default now you can you can definitely make this you know work the way you want with a lot of work because it's just code but by default your form is whatever size you develop it in and if you maximize it you get a whole bunch of extra space and if you resize it too small you cut off what's on the form there's no scroll bars here it's just you can create scroll bars that you know can do a job but it's ugly um so windows forms is kind of like what you see is what you get so that's something to think through now let's close this out i'm going to go back to my solution explorer and we're going to create a new project so we're going to create a new project for windows form app and recall this uh better winforms demo and yes.net six still so this is the the best practices for how to deal with windows forms so let's talk about when you first start your project up what do you do well i'm gonna start by saying a startup project so we first start this up what are the things that i do every time well first i'll come down here to win or to form one and i rename this so i click on it and click on it again or you can right click on it and say rename or hit f2 i'm going to say main form and it's going to say hey you're renaming a file would you also like to perform or rename this project of all references to the phone code element form one well yes i definitely would and so now if we right click and say view code notice it says partial class form or main form not form1 and if you go to program.cs it says mainform not form1 so that's the first tweak i do now whoops let's open that up i do want to point out one thing the eagle eye among you will see that it still says up here form one why is that because this is not a the class name it is actually just a the default value for a property let me go to properties and pin that and we go to notice it says text down here for properties it says form1 so i can say main form like so once you click out of it it renames i can say main form by tim corey something like that if you want to do a more descriptive thing with that that describes what your form is so that's the next thing i do is i rename uh or change the text of my form to be something more uh logical next up before i do anything else i come up here to font now because i'm on a demo with you let's unpin this i'm going to make my font into about 18 but for you you might want to go with a 14 or a 16 but even 18 is probably pretty good hit ok now this makes the form massive and this is one of those quirks in the editor that i'm not a huge fan of is it says oh since your form is bigger that probably means that everything else should relatively be bigger as well so since i went from 9 to 18 it basically doubled the size of everything width and height don't want that so use your scroll bars here you go to the lower right hand corner put your cursor on the um that little box in the corner click and drag and resize it back to a normal size now you could also go to the the form and go to i think it's width um oh size right here yeah there you go under size there's width and height you could change this to uh you know 500 and then 400 like so and notice how it resizes it for you there so you could just do that in the properties again these properties represent the values that are then displayed in the designer so if i just change this notice that my width and height change so that's the next thing i do though is i resize it after changing the font which the value of doing so is i come to common controls here and i say label i drag a label on like so notice that label is much larger the the text in it is larger because by default the font size is 18 instead of nine because the the default for your your text boxes your buttons your labels all the fonts of anything you dragging us form now the default value will be the current value of the forms font size and also font choice so if you chose arial instead that would be ariel 18 point but i want to point this out if i were to go back to form 1 in our original demo and i were to change this form let's go up to our form here and change the font size to be 18 hit okay it made a mess of everything but notice that oh it did change nice um let's undo this for a minute so let's just say that i changed and this is what i forgot okay it's been a bit but it did change all my font size it also stretched everything out which is horrible but let's just say i change first name to be 10 points okay 10 points there we go it's a little bigger now let's go back to my form and change this to be 18. first name is still tiny why is that because this no longer uses the defaults it uses its own value it's overriding the default and the default is where the form is but now that i've changed it it says well if you changed it that means that's what you want therefore i'll leave it at that size but it messed everything else and it caused all kinds of problems so really if you already have a let's change this back as well if you already have a form that's already started you really don't want to make some changes to your defaults anymore it kind of causes problems so let's hit save if you're on your new form change the defaults first and then don't mess them so now i can drag and drop this label on well let's give me a first name i'm going to change it label here to say first name but i'm also going to scroll to the very top of the properties where it says label one and it changes to be first name label now there's some important things to note here this is where some old school winform people are going to disagree with me and that's okay but i think i'm right so let's talk about it um first off i have used camelcase for my label name why well because if you think through what's actually happening here this name isn't a property it is the variable name for this element so if you were to create a new instance of class and give a variable name you would give it camel casing because it's a variable a private variable well that's what this is it's a variable called first name label so that's we're going to do we're going to name it as if it is a variable because it is second off i did not say lbl first name for label first name which is a had been a pretty common syntax for naming our variables back in the day remember that this came from the first version of visual studio of dotnet so net1 had windows forms and then it was really modeled after what we had in visual basic six and others with the drag and drop designer where i remember microsoft even recommending what's called hungarian casing so that's where you give the type in the name so you start off a text box with txt in a labeled lbl and the thought is it makes it easier to read but here's the problem microsoft actually did a 180 on this they used to recommend hungarian notation and now they strongly recommend against hungarian notation so if you're an old school microsoft person and you kind of grew up in this you say hey you know microsoft even recommends doing lbl or txt no they don't but yes they used to you're not remembering incorrectly they used to it's just that they changed with the times and the reason why is because it does not read properly so when remember code is meant to be read by humans not by compilers by humans otherwise we'd call this label a the next one b because it's more efficient that way but that's not what we're doing we're calling it first name label because it's meant to be read by humans when you read down through code it is easier and less jarring to read first name label because that's how you'd say it oh that's the first name label so if i said what is this you wouldn't say that's the lbl first name doesn't make sense but you'd say that's the first name label well that's what this is we have two spaces out so it describes what it is in a way that is easy to read in english so that's how we name things so that's first name label so next best practice is always name your objects and do it first okay so let's put a text box on here uh text box we'll drag it on you can align it notice different alignment points so top there's that line for the top bottom there's line at the bottom but there's one more for text boxes that's pretty important be dragged into a little bit more notice that there's a line goes through the text box and it's right underneath the first name and what this is is it aligns the text so the text in the text box will be in alignment with the text first name so that's usually i do for text boxes and labels what's the first thing you should do when you create any property drag any property out of the or object onto the the form come up here rename it first name text okay we can if you click on a form once and drag you can drag a selector select multiple things and you can move them around as one super helpful now let's put a button on here we're going to make this a little bigger we're gonna kind of position where you think we should um and i'm gonna remember first thing you do rename it so i'm gonna call this the um first or um say hello button okay and then down here i'm going to say say hello on the text there we go now by the way that's resizing that changes the height and the width and the size right over here it changes that based upon what i do so you can modify that however you want and then i can you know re adjust the form to fit and so on but why is it so important that i name things first instead of later maybe come back and do it later well the problem is if i double click on say hello notice what it did it created a method for me the event handler cool we know that but notice it says say hello button underscore click as opposed to what it was in let's go back over here to our form one where it says button one and if we go to the button one event it says button one so now here's a kicker if i come back over here and say oh i forgot to rename this go to properties here let's come up here to button one i'm going to say let's call it greet user button and we'll come down here and change it from button one to great user cool i fixed that problem awesome let's double click on again and it's button one didn't change that didn't change the name because this name argument created at this point so it's not gonna change it which means that if you come over here to form one's code and say okay where was that event for the greeting button and you can't find it and you have a whole bunch of button one button two button three button four events and you're like which one is it oh i've come over here and find the event which only works for the primary event not for the other events that are not the primary event because for those you have to come here select it then go to properties then go to events then find it and go always name button one underscore click okay and then you can actually double click there and go to it but that's why we name things first because then you go oh say hello button cool that's there okay now you can rename that there's ways to do that but i want to point out that's the basics of why we name things first also if you're not sure if you've named everything go to properties notice that up here it says say hello button that's what's selected if you click this is a drop down click it it shows you all the things my form now there's not many but this shows you anything that's named label one form one button one text box one all those kind of things in fact we go over to our form one and do the same thing we can see there's a lot more here we can see check box one um we have form one we have label one label two menu strip one progress bar one status strip one text boxes one through four tool strip progress bar one and labels so it's all these ones at the end you go oh that's a problem let's fix all of those now you kind of made a mess already because of all your events but at least you're making progress you can change those things for your events as well just takes a little more work so that's another best practice when it comes to creating your form is to label thing or name things right away it's also important because notice if i select these two things i can control c to copy and control well i'll wait for it to be done spinning um every once while you catch this designer off guard uh hit control v and it lines up and you go oh it's actually last name okay yeah it's more than that it's called label one so label one and text box one whoops need to fix that so come over here to the top and say this is last name label and then you can come over here and notice the it's kind of gray here but it's already selected the same property if they both have the same product which they both do they both have a name property so i can just start typing so last name text without clicking that's a little bit of a speed booster thing so now i have things labeled properly also try and name things the same so first name label last name label and so those are you know the same pattern but also first name label first name text those two go together last name label last name text those two go together so someone thinks through now let's run this real quick we haven't wired the button but that's okay and let's bring it over here and i say tim i hit tab and it goes to say hello i hit tab again then it goes to last name well that's that's not right my tab order's incorrect and that's because i created the first name and the the first name text box and then the button next well so the next thing i do is to check your tab order so let's wait for visuals to catch up we're going to go to down here where it says tab index of 1 and tab stop of true so what this is again for accessibility if you don't use a mouse can't use a mouse um whatever reason you can tab through the form in order using just your tab key but only if it's in the right order and only if the things that aren't selectable aren't selectable only if the things that are selectable are selectable um i hope that makes sense so tab index of one that's the first in the list notice the button says tab it next to two and this one says tab it next to four okay so how do you fix this well select this right here it's one cool this one should be the next one in order so let's make this two and this one should be three okay and they all say tab stop yes notice the labels say um doesn't have a tab stop on them because they can't be tabbed without belief um so tab stop one tab stop at two tab stop of our tab index of three so there we go uh tab index here i'm not i'm not sure why you even have this um but it can't tab to a label but let's try it which you can you can have the numbers don't necessarily matter you could say 1 10 50 if you wanted to and that might even make sense because you might say hey you know what we're going to possibly put things in the middle and so we're going to say 1 10 50 and then if we has that goes in the middle we can have a 45. um what happens behind the scenes is visual studio says what's the next one that is both tabiable and is next in line doesn't matter the number is so now even though we have our label starts at zero we can't tab to it so we've got cursor in first name we hit tab now our cursor is in last name hit tab again now our cursor is highlighting this button notice kind of the blue outline here if i already hit the space bar i can actually click the button let's just kind of verify that let's click on say hello well let's wait for the designer to figure things out let's come over here to our event and we're going to say again that message box dot show and we're going to say string interpolation we'll say hello first name text dot text and space last name text dot text see how the naming actually helps you out even if you didn't quite remember you'd say well i think it's the first name something well first name text the other thing that's going to mess you up let's just run this first and i'll talk about that because it's important okay so tim tab cory tab space hello tim corey i hit space again close it out now if i hit tab again it goes back to the beginning at tim because that's we we got to the end of our tab stop so we start over at the beginning now the first thing's going to trip you up at some point or not the first thing but one of the things going to trip you up at some point is you're going to do this first name text last name text cool you run this and it even seems to work so you're going to say tim corey say hello hello assistant.windows.form.textbox text tim system.windows.forum with textbox text corey you're like that's not what i was expecting well the reason why is because you use the entire object again object oriented programming you use the entire class and this class does have a default tostring method that actually prints out more than just the name of the class it prints out all the properties that are non-standard i believe it might just be the text i'm not positive because what you should be doing is specifying which property you want i want the text property okay there you go now that will work properly so there's not a little pitfall for you to avoid now when it comes to multiple forms we're going to wrap this up pretty soon but when it comes to multiple forms so i want you to think through is the fact that when you instantiate a new form it's just a class with a constructor which means if you want to pass values to another form let's just do that real quick um if you want to pass value to another form let's do this down here we already have formula and form two so let's say we want to change have a i'm gonna copy and paste this and i'm not gonna change the name i know it's it's it hurts me but um this is label two so where it says form two wrong wipe this out and there's nothing a value here yet but when i open up my class for this so view code i'm going to change form 2 to say string message and i have a private string uh form message like so and then i'll in here say form actually there you go for message equals message it's helping me out and then i could actually even right in here say label 2 dot text equals for message so i'm saying to the constructor you don't just have an empty constructor you want to take in a value which means that if i were to come over here to form one's code and just try to let's comment these out and let's uncomment these if i try to do this it goes you need to pass in a value of message to the constructor so we can say hello from form one like so now let's set it back to startup project and run this and if i were to say greet user it opens a new form it says hello from form1 it passed data from one form to the other so you can pass it in and you can even pass in the instance of this particular form in the constructor so they can call things back the other direction there's lots of cool stuff you can do with windows form i actually go into a lot more depth in the tournament tracker application it is a.net framework project that we do but all the same things apply and i do have a course actually that upgrades the tournament tracker application to net core 3.0 i believe so it's possible to upgrade.net core but i just want to show off that you can pass data back and forth because it's just a class this is where again i really don't like it when courses say windows form drag and drop is the place to start as a developer because it's magic but when you understand object-oriented programming when you understand inheritance and interfaces and constructors and properties and methods and events then you go oh this is just a class and i can use this class to do pretty much whatever i want because it's like any other class i sheet i can create multiple instances i can have multiple constructors i can pass instances into other classes and pass them back and all the rest the cool stuff you can do with object oriented programming you can do in winforms it's just you'll have a visual output for it instead of just uh it being logic or data access or something else so that's the next thing that you can do with winforms that's important to know about let's get back to our best practices though another best practice and this is again i am old school i have seen this done i have done this many times please learn from my mistakes don't do this okay right click on your main form go to view code it's awful tempting awful tempting to put all of your code here in fact people say well how else can i data bind directly to my sql server than if i if i don't put my code right in the code behind for main form guess what you shouldn't be data buying directly to your sql server sorry just don't do that because yeah it works until it doesn't it works until you have two three four thousand lines of code in the code behind yes i have seen that yes i have participated in that that's almost entirely a bad idea because when it comes time to change over maybe you say you know what this idea of the form just doesn't resize like it it is what it is and it's messy and we don't we want to have more responsiveness we want to use the graphics card this does not use the graphics card when it comes to rendering things we want to have some more interactivity all that good stuff we want to be able to do all that we can't do it as easily and when a formula change over to wpf well guess what you have to rewrite your entire application because all of your code lives here don't do that instead create a class library put all of your code in the class library except for the code that specifically interacts with the user interface code is user interface code and it stays in the winform project but for example even this right here would probably end up being in the class library it's called a method that says here's the data give me the the data to display okay put as much as possible in your class library that way when it comes time to replace your user interface you can do so much more easily when it comes time to upgrade your user interface you can do so much easier when it goes from net6.net 7 when if you are using a you know for example maybe you went all in on uwp and then microsoft says and we're deprecating it we still support it but we're not doing anything new for it and you go oh but i want new stuff i want to move to maui well if you had put all of your code in the code behind you've got a problem you've got work to do but if you had put all of your code that you can into a class library it's much easier to swap those out so if at all possible put 90 plus percent of your code in your class library and just reference it that's my next best practice so for example data access should not be in your user interface just shouldn't be there put it in your class library all right so that's my next best practice for win forms um winforms can be a great type oh let's let's do one more tweak it's not best practice but tweak put my semicolon here and make this a file scope namespace yes you can do that windows forms makes things easier makes it four less spaces horizontally so all right with that um that's kind of the best practices for windows forms there's a lot more depth to go into but as you can see this has already been a pretty epic video um i wanted to just get into the topic of how to get started and win forms how to use them and when to use them and again when to use them once you know c sharp pretty well don't start here don't make this your starter project until you know c sharp really well that's why i teach beginner c sharp out of the console application because console application isn't using or is not um we're not making use of the inheritance structure nearly as much and there's not a lot of magic there it's just pretty simple stuff because we want to focus on learning c sharp and people often say you know should i if i'm learning i want to learn c sharp so should i do wind force well no and they may say well okay should i learn asp.net core instead and stop pause those are user interfaces winiforms wpf uh uwp.net maui blazer uh mvc api razer pages these are all user interfaces even console to user interface what you want to focus on is learning c sharp the code you might say well tim i want to be a woman form developer well yes as you've seen all when forms is is classes instantiation properties events and so on so when you learn c-sharp you are learning almost everything you need to know about windows forms and windows forms the stuff you need to know is just a little bit ad on top that you inherit from like that's that's really the the big deal once you know c sharp but if you don't know c sharp then this is just magic and it just works you drag and drop and when the magic breaks bad things happen so i encourage you learn c sharp first then choose which user interface you best want to learn and start with that but don't get caught up in saying i'm only going to do dot net maui or i'm only going to do mbc learn the different user interface types because knowing multiple is very helpful because even if you are a web developer there are times when you could use a little utility and almost always little utilities need to be desktop applications web applications and utilities just don't work that well they don't do what they're designed to do and they're more complicated they need a web server to host them and all this stuff just create a little win format i have multiple little utilities on my machine that i do for various projects to make to automate some of the things that take time otherwise it makes my life easier and i do that through console apps i use that through winform apps um everyone saw a wpf app but almost always it's either console or a winform app so i encourage you get to know the various prototypes but learn c sharp first i hope this answers a lot of your questions around getting started in winforms though if you have other questions leave them down below i also have a suggestion site so suggestions.iamtimcory.com if you want to see a future topic covered like if you know if you want to say hey i want more depth on winforms or you know where i go for this then go to uh suggestions.iamtimcory.com and leave that suggestion there i'll also kind of prompt you to go there if you leave that type of suggestion on the on the youtube comments because i don't have a way of keeping track of youtube comments there's just thousands that come in every week and i barely even see them all so trying to keep track of of who suggested something three months ago is difficult so that's why we have a suggestion site where you can go and leave a suggestion vote on a suggestion and hopefully see your suggestion answered in a future uh video here on youtube so with that like i said if you have any questions leave them down below i'll try to get to as many as possible if you want to go further you want to know what the other product types are or how things fit go to csharpprojects.com [Music] i have a site there that gives you an overview of all the different project types from visual studio how to get started in them how to go deeper in them where they fit in the overall ecosystem of net and so on so i encourage you to check that out as well thanks for watching and as always i am tim cory [Music] [Applause] you
Info
Channel: IAmTimCorey
Views: 194,802
Rating: undefined out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# course, C# training, C# tutorial, .net core, vs2022, .net 6, winforms, windows forms, desktop application
Id: 0zLZQesgV5o
Channel Id: undefined
Length: 95min 49sec (5749 seconds)
Published: Mon Aug 08 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.