JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Embedding Visual Basic Code in Web Pages

In fact, it's possible to embed Visual Basic code directly in ASPX files—no ASPXVB "code-behind" file needed. However, in this case, you're responsible for writing all the code yourself—the Visual Basic IDE won't help with IntelliSense and other features.

There's an example, EmbeddedVB, on the CD-ROM showing how this works. You can see this example at work in Figure 14.19—just click the Click Me button and the message "Hello from Visual Basic!" appears in the text box after a round trip to the server.

Click To expand
Figure 14.19: Using Visual Basic code embedded in a Web page.

To make this work, I've written WebForm1.aspx for this example by hand. In this case, I've created a button and a text box using the <asp:Button> and <asp:TextBox> elements, and made them into server controls by setting their runat attributes to "server". I've also placed the Visual Basic code for the button's event handler, Button1_Click, in the ASPX file itself, in an HTML <script> element with the language attribute set to "VB" and the runat attribute set to "server" so this Visual Basic code is run back at the server. I've also connected the button's Click event to this event handler by setting the onclick attribute of the <asp:Button> element to "Button1_Click", like this:

<%@ Page Language="vb" AutoEventWireup="false"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  <HEAD><meta name=vs_targetSchema content=" _
<TITLE>EmbeddedVB example</TITLE>
   <script language="VB" runat="server">
    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs)
        TextBox1.Text = "Hello from Visual Basic!"
    End Sub
   <form runat="server" ID="Form1">

<asp:Button id="Button1" Text="Click Me" OnClick="Button1_Click"
<asp:TextBox id=TextBox1 runat="server"></asp:TextBox></P>

And that's all it takes—now the Visual Basic code in the button's event handler will be run back at the server, even though this code is actually stored in the Web page itself, not in a ASPXVB code-behind file on the server. Whether or not you write your code this way is a matter of choice—if you consider yourself an ASP .NET programmer, this is often the primary way you'll write code. Visual Basic programmers, however, often prefer to stick with the Visual Basic code and code designers that they already know how to use.

Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor