Tuesday, 26 July 2011

Using Shared Code in ASP.NET and VB


This tutorial shows how we can create our own classes and use shared code between different pages on our website. VB version.

Visual Studio allows you to create classes in separate files to be used in multiple pages on your website.
Classes you create are stored in the App_Code folder and can be in any language you prefer. For this tutorial, we'll create a sample class:

Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls

''' <summary>
''' Summary description for TestClass1
''' </summary>
Public Class TestClass1
Public Sub New()

End Sub
Private testStringValue As String
Public Property testString() As String
Get
Return testStringValue
End Get
Set(ByVal value As String)
testStringValue = value
End Set
End Property
End Class

We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

When called, the class can either store data or return data. We create a text box and a button to show how we can store data in a variable in a separate class, and then a label to show how we can retrieve that same data.
The ASPX page which is using the class function:

<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>&nbsp;
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />&nbsp;<br />
<asp:Label ID="Label2" runat="server" Text="Yout typed in: " Visible="False"></asp:Label>
<asp:Label ID="Label1" runat="server"></asp:Label></div>
</form>

We are using Server Intellect and have found that by far, they are the most friendly, responsive, and knowledgeable support team we've ever dealt with!

The code-behind should look something like this:

Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls

Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim tc As New TestClass1()
tc.testString = TextBox1.Text
Label1.Text = tc.testString
Label2.Visible = True
End Sub
End Class

Looking for the C#.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

No comments:

Post a Comment