Events
<form id="form1" runat="server"> <div> <asp:Label runat="server" id="HelloWorldLabel"></asp:Label> <br /><br /> <asp:TextBox runat="server" id="TextInput" /> <asp:Button runat="server" id="GreetButton" text="Say Hello!" /> </div> </form>As you can see, we now have the 2 new controls added, but they really can't do much at the moment. You can run the example if you wish to check this out for your self - if you click the button, the page is simply reloaded. Let's change that, and let's start by doing it the easy way. VWD comes with a WYSIWYG editor, and while I hardly ever use it my self, it does make some things easier, like creating events. So, click the Design button in the bottom of VWD. Now you will see a visual representation of our page. We wish to add a Click event to the button, and this is very simply - just doubleclick the GreetButton, and you will be taken to the CodeBehind file of our page. As you can see, a fine new method has been added, called GreetButton_Click. If you have a look at the Default.aspx file (you need to go from Design view to Source view), you will see that an attribute has been added to our Button control, telling which method to call when the button is clicked. All this work done with a simple doubleclick.
Now lets add some code to our new event. We wish to use the text from the TextBox, on our good old Label with the "Hello, world!" text. This is also very simple, and all it requires is a single line of code:
HelloWorldLabel.Text = "Hello, " + TextInput.Text;Run the project again (F6), and you will see the our old page with a couple of new controls. The "Hello, world!" text is still there, because we set it in the Page_Load event. Now try entering a name in the textbox, and press the button. Voila, the text is changed, and we have just used our first control event. Notice how we can add code which is not necessarily called unless the user performs a specific task. This is different from the good old Classic ASP/PHP approach, but you will soon get used to it, and you will probably also come to like it a lot!
Having problems with this chapter? Ask in our forums!
© net-tutorials.com 2006 - 2010