Main

24 Understanding Event-Driven Programming

Learn how events are utilized in the .NET Framework Class Library specific to WPF and ASP.NET Web Forms applications. In these examples, we see how C# is generated by the IDE to "wire up" a user action or application event to the code that handles that event.

Akram F. Sulaiman

4 years ago

Hi, I'm Bob Tabor with www.LearnVisualStudio.net where I teach beginners the skills they need to get their first software development jobs building Windows and web apps at the world's best companies as quickly as possible. So up to now we've been focusing purely on the C# syntax itself as well as some utility classes from the .NET framework class library. We've looked at some other matters related to the compilation of source code into assemblies, we looked at the .NET framework run time, what h
appens at run time and so on. However, I'm sure at this point that you're now getting ready and you're itching to build real applications, you know, applications that have real and attracted users interfaces, whether it be web-based applications or Windows-based applications. So in this final tutorial video, we're going to be discussing event-driven programming. Event-driven programming is really at the heart Microsoft's presentation API's and, for that matter, it's at the heart of just about ev
ery other API in the .NET framework class library. It allows you to plug in and handle key events in the life cycle of the application's execution and even replace the default features of .NET. So we're ways off from performing those types of operations, but it all starts with the fundamental understanding of events. So up to this point in our simple Console Window applications, there's really been only one event that occurs. The application startup event, which in turn triggers the static void
main where we wrote the majority of our code. However, in a modern users interface, whether it be a native Windows application or a web-based application, users can interact with the elements that they see on screen. They can hover their mouse curser over elements, they can press keys on the keyboard, they can type text into fields, and they can drag and drop the various elements that they see on screen and so on. And as a software developer, you can write code that responds to these interaction
s. So when these interactions happen, .NET runtime raises events to you as the developer and you get to decide which events that you want to respond to and what should happen whenever that event is raised. Speaking specifically about the users interface, every single control, whether it be a text box or a button or a drop-down list box or a grid, or whatever the case might be, each of those have different events that can you write code to respond to, or to handle. And we'll show you more about t
hat in just a moment. So how does this manifest itself in the applications that you're going to write? Well, in this lesson I'm going to demonstrate how you get the same experience of working with events whether you write a Windows application or a web application, thanks to Visual Studio and the API's that are available through the .NET framework class library. What I want to do is start off by creating a new project. And we're going to actually use a different template this time. So we're goin
g to choose the WPF application template. So WPF stands for the Windows Presentation Foundation. It's actually a subset of the .NET framework class library and its specific job is to allow you to create native Windows applications as opposed to web-based applications or Console applications like we've been building up to this point. You see that there's also in this template something called the Windows Forms application. We could have easily used that template for this example, but frankly Wind
ows Forms is a little bit older API that was available when .NET first came out in 2002. Admittedly, it's still used by many programs and many programmers in many companies that build Windows desktop software. But honestly most of the buzz nowadays surrounds WPF, not Windows forms. All right? Having said that, what you're going to learn in this lesson by creating a WPF application will still mostly apply to Windows forms as well. So let's do this, make sure we've created a WPF application, and w
e're going to call this WPF "events" and then click okay. I'm not going to take the time to actually explain everything about XML or WPF or even some of the interactions that I take with the application here. I'm going to leave a lot to the imagination. There will be a lot of series that cover all of this content either where you're currently watching this video on Microsoft's website, or on my own website, LearnVisualStudio.net. However, we just want to point out those things that will really l
ead us to understand more about event-driven programming for this lesson. What we're going to do is start with a tool box and we're going to go to common WPF controls and we're going to use the little arrow that's pointed towards that word and then we're going to click it. And now the arrow points down and we can drag and drop controls from our tool box on to this design surface here in the middle. And so the first thing I want to do is drag a button and drop it on to our design surface and then
drag a label and drop it on to our design surface beneath it. So now I'm going to select the button control, I'm going to come over here to the properties Windows and I'm going to give this button control a name. I'm going to call this "my button." All right? And then I'm going to select the label control beneath it and I'm going to call this "my label." Furthermore, I'm going to go down to the content property here, and it has by default the value "label." I'm going to delete that and hit ente
r on my keyboard, and so now the label will be pretty much resized to be very small. All right? Should see a second tab open in the main area called "main window.XML.cs." So we want to select it to make the tab that's currently visible. And if you don't see this tab then you'll want to go to the Solution Explorer and you'll want to find the entry "main window.XML," and you'll want to click that little arrow that's pointing towards the word and click it once to make it point down. This will show
that there's a related file called "main window.XML.cs." And you can merely just click it and it should open it up in the main area. What we want to do is go down to this constructor for the main window class and beneath "initialize component," what I want to do is type in "my button.click plus equals". Now you see IntelliSense pops up. The first one says "Do you want to create a method name called my button underscore click?" and it just will default to whatever name we've given the control, in
this case "my button," and since we're handling the event by choosing the ".click" on the end of "my button," it assumes that we want to create a click handler. So this is just a way to enforce a naming convention, that's all. I'm going to hit tab on my keyboard once to insert that. Now that we've decided on a name, "my button underscore click" will be a new... I would say helper method I guess you could call it, a method to handle the click event. It says "IntellliSense says to press tab to ge
nerate the handler my button underscore click in this class." And I'll click the tab button one more time. And notice that it creates a void "my button underscore click," and then it has these input parameters. And these will be sent in from the .NET framework, specifically from the Windows Presentation Foundation engine. And notice that it has one line of code already generated in that method stub, that stubbed out version of the "my button underscore click event" handler. This little snippet w
ill remind you in case you forget to write your own code for the event handler. So let me just show you how that works. I'm going to go ahead and start the program at this point. And I'll click the button, and it will throw an exception. And we'll go ahead and click continue. But that's not the behavior we want. We're actually going to comment out that line of code and replace it by setting a property of "my label." So we have the "my label" object, and we're going to set its content property, s
et it equal to "hello world." All right? This time when we start debugging the application and we click the button, notice that our label control now displays the value of "hello world." So what was the significance of this little exercise? Well, it was not to teach you about WPF. Again there will be other lessons for that. It was really to teach you about the nature of event handling and how to handle events. So events can be raised in one of several ways, either by the .NET framework runtime,
by end users, like in our case here where we actually clicked on a button in order to kick off an event, or there are some other instances as well. Windows Presentation Foundation, each window, or control, or even those objects that don't have a visual component, like those objects that control the navigation between multiple Windows, or those objects that handle communication with the network or file storage, all expose some events. And as a developer, you can choose which event that you're goi
ng to respond to by writing code in a special method called an event handler, like we did here. What's so special about it? Well, as you can see, typically they're method signatures defined by the object itself. In the case of the button control, the click event requires an event handler be defined that accepts two input parameters. First, the sender of type, "system.object," and that represents the caller that fired off the event. And then second a "routed event ARGs," simply called E, that con
tains extra information about the call. And there's something to routed events, and we don't want to talk about that right now. But it's just extra information that might be passed along to the event... or rather the method that will actually handle this. Many times you can just ignore these input parameters, but occasionally they will allow you to access some important details set by the caller of the event. So the key idea so far is that we attach the new event handler to the click event of th
e button, and then using that special plus equal syntax... we've seen that before; remember? Whenever we were trying to append several strings together, we saw how we were able to use that. Well, this is kind of the same idea. And we'll talk about that in a little bit. Basically Visual Studio helped us to write that code by automating some of it with helpful IntellliSense prompts and code snippets. I use the term "attached" to an event. Some people call this registering an event. And we can use
this same style of syntax to actually attach multiple events handlers to a single event and even programmatically remove the event handlers using the minus equal operator. So there might be a reason why we want to, in a separate event, go ahead and do this one more time. This time we might want to call this "my button, I clicked this," and then we would have to create an event... you can even copy and paste this one... and change this to "I clicked this," and we can call this "hello world again.
" And we'll see what happens whenever we run this. You might say, "Well, it only said hello world again. Where did the first event go?" It fired off, but immediately was covered up by the second, the change of the content property the second time. It was almost instantaneous. In addition to this "imperitous" style where we're actually writing C# code, there's a way to attach an event to an event handler declaratively. So while we work purely in the design pane, whether you realized it or not, we
were generating some code down here in this area below it that was called XML. And XML is an XML syntax for creating instances of objects. And I explain XML in depth in another series, but if you look at the example here, you can see that I could have accomplished essentially the same thing... let me go ahead and separate these out on the different lines here. I could have accomplished essentially the same thing by doing something like this. So as you can see there are different ways to wire up
or attach or register an event handler with an event. Before I end this project and I move on to the next one, I wanted to expand on what I said at the outset of this lesson. Every control has quite a few events that you can choose to handle or ignore, depending on what you wanted your application to do. And you, the developer, get to decide that. So to see a comprehensive list of all the events for a given control or a window, whatever the case might be, just go ahead and make sure that you're
selecting whatever the object is, either in the XML view or on the designer surface, and then go to the properties window, and then click the little lightning bolt icon in the upper right-hand corner. And that will show you a list of all of the events that are available for just the button. So there are things about dragging and dropping, there are things about focus and mouse capture and stylus capture and touch capture, things to check if the mouse is captured or not, keyboard, so typing on t
he keyboard, key up, key down, and all sorts of stuff. So there's dozens. So some of these events deal with lay out and positioning at the time when Windows was first loaded up and displayed to the users, allowing you to preempt that process and perform additional layout and positioning logic. Some events deal with keyboard access, like we saw, or keyboard interaction. Some events deal with the stylus, when a user is accessing the app from a tablet. Some events deal with normal mouse operations
like click or hover or drag and drop. Some of these events work together addressing smaller parts of a bigger operation such as drag and drop. And the challenge won't be getting access to given control or event... elements events, but it will be determining the nuance difference between the events and picking the right events that you wanted to handle. Also, each event will be raised in a different order. And sometimes the logic that you write is expecting a certain order of the events to occur
and it just doesn't happen that way. And so subtle bugs are introduced if you don't understand the actual order of execution of each of the events in the event handlers. These Are just the events for the button control. There are event for everything. For example, for the main Windows itself. So we wrote code in the classes constructor, in the main Windows constructor. But there are other events that happen as the windows is loaded or its unloaded or its moved or it's resized. And there are even
ts concerning the live time of the entire app as well. The app is beginning, the app is ending, and so on. In the case of a WPF application, those events are handled in this file called "app.XML" and "app.XML cs." So at this point, the main take-away is that there are events everywhere you look. If you can dream up an action that you want your application to perform or respond to, your first thought should be "what events should the application be responding to" and then you do your research on
MSDN using your favorite search engine to locate the right event for the job. To reinforce this idea, I wanted to practically duplicate this entire example we just created, but this time building an ASP.NET web forms application. So my goal is to show you that, first of all, understanding the nature of events is important whenever building applications in .NET. And then secondly, much of the knowledge that you gain from one API can be applied to other API's as well. In this particular case, we'r
e going to transfer the knowledge that we gained from developing a Windows desktop application to creating a web forms application. So one thing that you need to understand is that off camera I installed Visual Studio 2013 Express For Web. And if you want to follow along, you're either going to need to follow the general instructions that I gave for installing Visual Studio 2013 express for Windows desktop way back in Lesson 2. Obviously you want to select the Express For Web Edition instead of
Express For Windows Desktop. Or you're going to need one of the commercial versions of Visual Studio like Professional or greater. Or alternatively you can just watch and still get the basic point of this lesson. What we're going to do is I'm going to go to and find Visual Studio Express 2013 For Web. And let me go ahead and pin that to my task bar, and then I'll go back to the desktop, and it should be there, and it is. So let's open that up. So I'm going to select the "new project" option from
the start page. But you can go "file, new project" or any of the other techniques that we've seen previously. And in the new project dialogue, I wanted to make sure to select the Visual C# templates. And in the center I want to select ASP.NET web application. We'll just ignore everything else in here. And I'm going to call this "ASP.NET events," and then okay. When I do that a new dialogue will pop up, the new ASP.NET project dialogue. And I'm going to select an empty template and then click ok
ay. All right. The very first thing I want to do is add an ASP.NET Web Form which is a file with an extension .ASPX, so I'm going right-click the project name in the solution Explorer and select "add" and select "web form" and it asks me to give the web form a name. And I'm going to call this "default" and click okay. And this will create the default .ASPX page. You can see it here in my Solution Explorer. It opens it up in Source View automatically here so that I can see both the HTML plus the
ASP.NET web form declarative code that's been added to the page already. I'm going to switch over at the very bottom here to "designer view." So now we're not looking at HTML or the declarative ASP.NET code, instead we're looking at a designer that's very similar to what we saw when we were working with the WPF application. And here what I want to do is drag and drop a button on to the designer surface. And right next to it I'm going to drag and drop a label onto the designer surface. Let's star
t with a button. I'm going to change the button's ID or its name to "my button" just like we did in the WPF example. And I'm going to come over to the label and change its name to "my label." And then I'm going to also remove its text property, which is equivalent to the content property of the label control in our WPF application. So I'll just delete that and hit enter on the keyboard. The next thing that I want to do is just go back to the Solution Explorer and I'm going to drill down into the
default .ASPX page. You can see that there are files that are associated with it. So I just clicked the little arrow next to it. And I want to double click this default ASPX.cs file. And inside of this event that the page handles called "page load" so when the page loads, we wanted to fire off the code of this event handler. And what we'll do is "my button.click plus equals"... this should all look familiar; right... "tab, tab." I'm going to comment out "throw new not implemented exception," an
d set "my labels.text equals hello world." And I'm going to save my changes and I'm going to use the run button. Notice that it doesn't say "debug" or "start," it just says "Internet Explorer," because it's going to open up my application in Internet Explorer. It opens up this little web server here IS Express, which will host my web application on a temporary basis. You can see I have my little button on a web page and I'm going to click that button, and there's a quick refresh of the page, and
I see the words "hello world" printed in the label control. Awesome. And just like what we did in the example of the WPF example, I can set that declaratively as well by going to the button and choosing on "click equals" and then I could create a new event from here or choose the "my button, click" instead of writing the code manually to writer it up or to attach the event handler to this event, the on click event. So I could actually create a second event and call this "my button underscore cl
ick one," which is the automatic name. And if I were to look then inside of the default.ASPX.cs file, you can see it created a new event handler, a new method with the name, "my button underscore click one." All right. And we can just delete that and we can go back in here and do this and it should still work. And finally, just like we saw previously with the WPF application, we can inspect all of the events associated with the given control. For example, by selecting the button I can then choos
e the little lightning bolt icon, the events icon, and see all of the events, the server side events available for the button control. Admittedly, there are far fewer events. And this is because the ASP.NET code that you write is executed on the web server. If you want to handle some more interesting client-side tasks, then you would choose a client-side technology like JavaScript or jQuery, and other languages and API's that can be executed in the web browser itself. And if that interests you,
you should definitely check out the Channel9 JavaScript and jQuery Fundamentals For Absolute Beginners, a series that I recorded a couple of years ago. Okay. So when you are interested in building a web form or a Windows form application, at this point it just becomes a matter of learning the different controls that are available for each and learning the different events that are raised by those controls. So what's the behavior of those controls that I as a programmer can write code to handle?
Well... start over again. Okay, so to recap, whether you're interested in building a web form or a Windows form application, at this point it just becomes a matter of learning the different controls that are available for each and learnings the different events that are raised by those controls. What's the behavior of those controls that I as a programmer can write to handle? Well, in my experience, about 75 percent of events are common across those controls. In most cases you can anticipate the
events that will be available without having to memorize a list or anything like that. Here's what I recommend. Whenever you need a particular control in your application, simply peruse the names of the event for that control. If you find one and you're not really sure what it does, you can just click on it and either look at the description below, like we're doing here. See there's a description of Inid, a description of a load listed write below it, or you can look up online in MSDN. Sometime
s the message that's associated with a given event could be a little bit cryptic in the help admittedly, but usually you can find some examples and some discussions online about what a given event will do for you. Usually that means that I need to get a more comprehensive understanding of a particular concept as a whole, like data binding or like the life cycle of a web form or web page or Windows form or the purpose for a given control. I might need to have a backup and understand a little bit
more about what does this control really do for me? I need some big picture information. And once I have that in place, the individual events will make a lot more sense to me typically. So I rely on MSDN every day, searching on MSDN a lot during this process of just gathering information and trying to understand what each of the controls do. Also, fundamentals of learning any API is learning the life cycle of events that occur during the execution of your application. For example, this URL discu
sses the ASP.NET application life cycle for internet information services 7.0. And this URL discusses the ASP.NET page life cycle. So the difference is the application itself versus an individual page's life cycle. And admittedly, these are very meaty topics, but they're really the key to understanding what's going on under the hood to deliver a dynamic page via ASP.NET. Similarly, there's a good jumping-off point for learning about the lifetime of WPF applications at this URL. So at some point,
becoming either a web developer or a Windows desktop developer will mean gaining a grasp of these topics, and it all starts with events, like we learned about in this lesson. And fortunately, you can leverage what you learn in one API and use it in other API's. So you learn a little bit about how events work in Windows forms, it will transfer over to web forms as well. And that was the whole intent whenever they designed these complementary technologies. Okay. We're done I think. Let's wrap it
up in the next lesson. You did great. We'll see you there. Thank you.

Comments