Lesson 3
Writing Code to Handle Events and Set Properties
Hello again. If you have already watched the first two video lessons you are probably wondering by now when are we going to get to start writing some code. So the answer is, we're going to start right now. In this video we will talk about events and how to handle events that occur within your application by writing some code. We will keep the code simple for now by setting properties of runtime for the controls on our forms. And over the course the next three or four videos will tack on more of the C# language so that you can include it in your applications. So let's get started by talking about events.
Visual C# 2005 Express Edition helps you create event-driven programs. Now what is an event driven program? All that means is that your applications will respond to events. And an event can be something as simple as "program started" or could be "user clicked button" or may be its "user typed a certain key on the key board," or any number of interactions between your program and anything else that's outside of that program. Your users are just one source of events. Windows itself can send messages to your applications like "shutdown" or "data coming from the internet to be processed." Other programs can trigger events in your application as well, and as I will demonstrate in just a moment there are literally hundreds of possible events that your application can react to. Now with all honesty, I'm oversimplifying events just a little bit here. But I think we can use this as a working definition throughout this lesson series. Now once you move on and start advancing your skills, you are going to realize that there are so many things that you can do with the events because it all depends on what events are. But I'm going to leave that for another time. Let's take a quick look at the "Hello World" application from lesson one. Let's talk about the single line of code that we created to display a message in a little message box on screen.
Now if you can recall from that lesson, what we did was double-click on the button that we added to the form and when we double-clicked on it, it brought up a code view. I think I made this point at the time that at the point that we double-clicked on the button, an event handler was created for us. What is it an event handler? This is the definition of the code block that would be performed whenever that event was triggered, in this case the event is given a default name "button 1_click," and then there are some other words that are on that same line like "private," "void" and "object," then our "EventArgs" and things of that nature. It may not make a whole lot of sense right now; let's not worry about them, we will talk about them later. And underneath of that we have these two curly braces and I said at that time that we need to make sure that we write this line of code between these two curly braces. So this event handler defines a section of code that will be triggered and executed whenever that event is fired off by the end user clicking the button. So it gives this particular event a name "button1_click" and we can change the name although we probably don't want to do that right now. Now what are those curly braces? Well they define in C# a block of code, or rather code that either works together to accomplish a task, in this case the task is to handle that button 1 click event, or the code block is used to organize code, so if you were to scroll up and down this code view we just look at the other lines of code that are available here, you will see that there are more sets of curly braces. And the code view does something nice for you. It allows you to roll up and expand these code blocks. There is one called the "names1" that's right underneath something called the "namespace," and one that's underneath the class. You can see that it is kind of hierarchical, that some code blocks can own other code blocks and they are all defined by indentation and these little curly braces.
Now for the next few lessons we will just keep in mind that when we write code, we will be typing inside these curly braces like the ones for our particular event handler. And we're going to talk about the code block several times in the next few lessons so let's just keep that idea open that a code block is anything between two sets of curly braces. There is one other thing that we didn't talk about at that time and that was the use of the end of line character which is a little semicolon (;). Every line of code that we write has to end in a semicolon. Now you will notice that there are some lines of code that don't end in semicolons, like this line of code for example. The reason that is, is because it defines a code block called an event handler or method. So just to recap, events happen within your application and you write your applications to respond to those events. And events can come from number of different sources. And the way you respond to events is to write a code in a code block called an event handler. A code block is defined by curly braces. And each code block is given a distinct name, this case the name is "button1_." Now before we move on I want to introduce a new term. We called this block of code an event handler. But an event handler is a type of a more general structure called the method. We will be writing and calling or rather triggering our own methods in lesson six. 95% of the code that we write will appear inside of a method. So it's an important building block and I want you to start hearing that term now. Now let's get back to event handlers. Like I said earlier there are hundreds of possible events that we can write code to handle. The question is, how do you know what other events are available to you? Do you have to memorize hundreds of these events or commands? Absolutely not!
In Visual C# 2005 Express Edition, there are three ways to determine which events a particular objects, like a control for example, can respond to and then go on to create an event handler for it. The first and most obvious way was to double-click the object in the design view like we did actually in the first lesson. So in the case of a button the default event handler is a click event. So each controls default event will depend on what makes sense for that particular control. But most of the time the default event is at least one of the events that you'll want to handle like a click event for example. What if you need a handler event that is not a default event? Well the easiest way to going about seeing all the available events for say a button, or any other control, is to go back to the design view like I have just done. Go to the properties window for the given control, make sure it is selected, and then select this little events icon which looks like a little lightning bolt. When you click on it you are going to see the list of all the possible events that can be triggered for this particular control. And they are categorized as well, by action, appearance, behavior, and so on. So for example, if we wanted to respond to a leave command, so this button will no longer have to focus, what we can do is double-click, entery the property window and all of a sudden we have a new event handler that was created on that for us - "button1_leave".
Let's go back to the design view for just a moment and look at the all the properties. It's up to us to decide whether or not we want to handle any events for a given control. For example, labels - we may not want to handle any events for them. Even if somebody clicks on them we're going to ignore any type of event that happens. That's our prerogative as software developers.
But we also have the ability to handle each and every single event that is listed here. Now more often the not, you are not going to need to do that. In a simple scenario you may need to only handle one event, but in a more complex scenario where we have dragging and dropping, or you want to work with the resizing or repainting of the forms somehow, you might have as many as six or twelve events that you want to handle for a single control. That's very much on the high size. So this isn't something that you should spend a lot of time being concerned about. But occasionally you are going to need to work with an event that is different than default event that's available to you by just double-clicking on that given control. So the third way that we can create an event handler is actually for us to type them in ourselves. Now I'm not going to demonstrate how to do this because it is so much easier to use one of the previous methods that I just showed you. But I want to make the point that there is really nothing magical going on here. You can type all the event handler code in yourself. Visual C# 2005 Express Edition just does it for you, mistake free, in order to speed up the process of writing applications. So now you should understand a little more of the events. Let's get on to some more fun stuff, let's write something meaningful within those event handlers. In the previous lesson we looked at how to adjust the properties of an object, like a control using the properties window, and we talked about how this is just a shortcut to actually writing the code ourselves. So now we're going to start writing code in our event handlers that actually changes the property of an object on our form ourselves. Instead of letting Visual C# do it for us, we're going to take control and we're going to change those properties ourselves when we want to change them. So let's do this, let's create a new project.
And we call this lesson 03, click "OK." That won't make any changes to my previous project that was open. So I want to keep the example fairly simple still. So I go to my toolbox and I'm going to find the textbox, drag it onto my designer surface, and then I'm going to find a button and put that on my designer surface as well. Now what I want to do is whenever I click the button I want to change a property of the textbox., the property I'm going to change is the "text" property, so by changing it I should able to put a new message inside of that textbox . So I'm going to double-click the button to get the default event handler and then I'm going to type some code. So in order to access or reference that particular control I'm going to have to use its name. Now by default, each control is given a name; I think we already talked about that in the previous lesson. So for example button1 is given. the first button we put on our form is given the name button1. If we would add another button we would be given another name - button2 and so on. Same thing with the textbox - textbox1 and if we would add another textbox, textbox2 and its up to us to rename these controls by using the "name" property within the properties window right here. We're going to leave the default name for now and work with textbox1. So I'm going to double-click, go to my event handler, and here I'm going to reference textbox1, 'textbox1' and now what I want to do is reference a single property of that textbox. I want to reference the 'text 'property so I use the period key on my keyboard and type in the word "text", use the space bar, and then set that property equal to "Hello World".
And then I'm going to use my end of line character. Now why did I wrap the word "Hello World" in quotation marks? We talk about that in the next lesson, when we talk about strings. So let's just ignore that for right now and take it at face value. So now let's run our applications to see if it works. Click our button and the message Hello World appears. We have changed the property of the textbox, setting the text property equal to "Hello World." We can change just about any property on our textbox by using the same method, by referencing the name of the object using that dot notation and then typing in the property name and then setting it equal to some value - the appropriate value for the given property. Let's take a quick moment to point out some of the ways that Visual C# 2005 Express Edition helps you when writing code. So let's bring this up a little bit higher on our code view and I'm going to highlight this and use the backspace button on my keyboard to delete the entire line. Let's retype this line and talk about what you saw as I was typing this line of code. So when I started typing the word textbox1, did you notice the little window that appears? This is called intelle-sense it helps you in two ways, first of all it's a visual reminder of the names of the objects that might want to refer to when you are writing code. Now if I was typing along and I forgot to type the name of my textbox, this would be a visual reminder. So as I type, the options become more narrowly focused on what I'm typing and I can use the up and down arrow keys on my key board to traverse this list and see all of the available items that I could use.
So notice that this a pretty long list. I can go down quite a ways in either direction. And I will explain more about all of these items that you see here when we talk more about the .NET framework in more detail. And once I find the item that I'm looking for, I don't have to type the entire word out, which is the second benefit of getting comfortable with intelle-sense. All I need to do is select the next logical terminating character. Now in this case it's going to be a period and it's going to complete the rest of the word, so I don't need to type it all out. And it's going to give me a list of all the properties, as well as the methods and events that are available to this object. I'm just going to click that period. Now I only spelled this out halfway but you can see it is highlighted in textbox1, and notice that it completed the word for me. So this reduces my spelling mistakes and I have the added benefit of not having to type so many characters. I can type much more quickly if I get used to using intelle-sense. Now it's going to, by default, bring me to the default property for that given control. Now again, I can go up and down and look at all the properties as well as methods and events, you see the events have a little fire bolts or a little bolt of electricity there. And these methods have little boxes like they are moving and properties have little fingers that are pointing to a piece of information on a little form. So that's how you can differentiate what each of these is. We're only going to reference properties at this time. And the intelle-sense works similar to. When I write or type the letter "t" notice I get the word "text" that pops open. And if I need to go to "text align" I need to type the entire word "text" and then "a" will bring us to "text Align", or go back and it goes back to text, so some very neat functionality there.
Also you can see a little off to the right a little yellow message box that gives you a little bit of help as to what that property or method or event actually is there for. So it's just quick reminder as we look at the various properties and methods of what is does, it's get to set the current text to the textbox. Now again, let's move on and I'm just going to use my space bar and hit the equal button and then I wind up typing in the rest of this line of code. Now once you get good at utilizing the intelle-sense, it's going to reduce the amount that you have to type by, I'm guessing here, maybe 20%. And it will increase the accuracy of your code. Now of course that does require that you can touch type and you keep your eyes on the screen, which just comes with a little bit of practice. Now admittedly, we haven't written a lot of code just yet, but I want to get you started with a few good habits up front. And one of the best habits that you could possibly get into is to comment your code. A code comment is just a description of what a section of code is attempting to accomplish. You need to make your comments to remind yourself of your thought process or the reason that this section of code even exists. You need to do it so that it's in clear language. The comments don't get compiled into your program, and they don't make your application larger in any other way. They are just there to remind you and anybody who might work on this application after you of what you were trying to do. So we highly recommend that you use as many comments as would make sense. And there are two ways to create comments, the first way to create a comment is use two backslashes (//) and then type whatever comment that you want to make. "This is a C# .comment."
The other way to create a comment is to start with a (/) and then use an asterisk, (*) and now I'm going to demonstrate that this is a multi-line comment by using the Enter key several times on my keyboard. Then to stop the multiline comment, I'm going to put a final backslash. So to start a multi-line comment, you will use "/*" and to stop it you will use "*/". And here we can type anything we want because this is a multi-line comment. You can even see that comments are grayed out, they are kind of in a lighter shade of gray. This is to let you know that they don't really have any impact on your application. When you get started, it's easy to forget comments and even for some of those who have been doing this for a while we might forget to take some time to write some comments occasionally, but it is much easier to read through well-written comments and try to understand what the code is doing than to have to interpret on what the code is actually trying to accomplish by reading the code line by line by line. So I have more to say about writing meaningful comments at the end of the series of videos when we're building our RSS reader application. That's when it's really going to hit home the value of making good comments within our application. Okay, we're just about finished with this lesson, but while we're here in the code view I thought we could take a quick aside and look at a few more features so that you have a good comfort level. Since, after all, this is where you are probably wind up spending the majority of your time while creating software. A little bit earlier in this lesson we talked about how using the code view you can collapse and expand code blocks by using + and - buttons off to the left-hand side.
And that's convenient if you want to get some code out of your way and not view everything at the same time, which can be sometimes confusing to have this code available and visible to you, so it's nice that we can roll it up. Well the good news is that you can create your own regions, your little roll-up areas, in order to group together different methods that might have a common purpose or goal, or you can also create a region inside of a method like our event handler code, in order to organize long passages of code. So you can find out what you are looking for more easily.
Now in order to create your own region what we will do is to go to our code view and we will start off by using our # sign and type in the word "region," and then we will use a space or two here and then we can give this region a name. "This is a region," and to end our region, we just have to do something like this "end region". And here we can type in code or anything that we want; I'm just going to make a few comments. "Nothing in particular." Okay so now here you see the magic of the region, let's go ahead and click the little minus sign in order to collapse this area. And you will notice that there is a little box around our region, and we can even hover our mouse cursor over the region box, and it gives us at least a synopsis of the code that's located within that region. And we can expand it by clicking the little plus button.
So this is a great way that we can hide or show passages of code that might take up a lot of visual space and as we're searching through for another code, you may just want to hide it. Or give it some type of descriptive title. Here is another great tip in regards to writing comments. Say you find an answer to a question that you had while you are coding and it's something that applies to the application you are working on, you find a great MSDN article that you like to remind yourself exists so if you ever come back to this point of code you can remind yourself of this thought, what you can do in your comments is add a hyperlink. So let's go to this multi-line comment that we already have and type in an address, and notice that it has an underline underneath of it, and in order to follow this hyperlink, all we need to do is hold down the control button and then click the link in our source code, and it will pop open a web browser and navigates to that website. So that's pretty cool. And it's very useful whenever you're trying to document exactly what you are doing. You can also put it to any online documentation that you might provide for other developers who are working on the same project as you are. So these are just a couple of the useful tricks that you can learn to help you code more quickly, to find and understand what you already coded, to organize your code, and more. For now just be aware of them and then we will build on these in our future lessons.
If you enjoyed this video please visit www.learnvisualstudio.net to download and watch over 500 videos just like this one aimed at all skill levels on many different topics related to C#, Visual Basic.NET, ASP.NET, and more. Thank you.
|