Welcome to Asp.net, vb.net, C#.net Resources Sign in | Join | Help

ADO.Net

Sharing Code Between Pages using ASP.NET 2.0 and VB.NET
This tutorial will show you how to share code between pages using ASP.NET 2.0 and VB.NET.

Although you can place code inside each page within your site (using the inline or code-behind separation models described in the previous section), there are times when you will want to share code across several pages in your site. It would be inefficient and difficult to maintain this code by copying it to every page that needs it. Fortunately, ASP.NET provides several convenient ways to make code accessible to all pages in an application.

The following example demonstrates an App_Code directory partitioned to contain files in both the VB and C# languages.
Using default namespace in the example.

First you need to build a CustomClassCsharp class in the folder Subdirectory.the code as following:

using System;

/// <summary>
/// CustomClassCsharp summary
/// </summary>
public class CustomClassCsharp
{
public String GetMessage(String input)
{
return "Hello from C# " + input;
}

}

 

Secondly, build a CustomClass the code as following:

Imports Microsoft.VisualBasic

Public Class CustomClass
Public Function GetMessage(ByVal name As String) As String
Return "Hello " & name
End Function
End Class

 

Thirdly,build a web.config file Site.master.the code as following:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation>
<codeSubDirectories>
<add directoryName="Subdirectory"/>
</codeSubDirectories>
</compilation>
</system.web>
</configuration>

The front end SharingCodeBetweenPagesCsharp.aspx page looks something like this:

<div align="center">
<b>Enter Your Name:</b>
<asp:TextBox ID="TextBox1" Runat="server"/>
<asp:Button ID="Button1" Text="Click Me" Runat="server" OnClick="Button1_Click"/>
<br />
<br />
<asp:Label ID="Label1" Runat="server" />
<br />
<asp:Label ID="Label2" Runat="server" />

</div>

 

The flow for the code behind page is as follows

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim c As New CustomClass
Label1.Text = c.GetMessage(TextBox1.Text)

Dim c2 As New CustomClassCsharp
Label2.Text = c2.GetMessage(TextBox1.Text)

End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub
End Class

 

 

This tutorial is provided in part by Mega Solutions Mega Solutions Inc.

Visit http://www.megasolutions.net for more ASP.NET Tutorials and Resources

Published Saturday, February 02, 2008 5:20 PM by admin

Filed under: , , , ,

Comments

No Comments
Anonymous comments are disabled
 
Powered by Community Server, by Telligent Systems