DotNet Tutorials

V4 Dot Net Tutorials

Server Intellect Cloud Hosting

 Using Shared Code in ASP.NET and C#

This tutorial shows how we can create our own classes and use shared code between different pages on our website. C# 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:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for TestClass1
/// </summary>
public class TestClass1
{
public TestClass1()
{

}
private string testStringValue;
public string testString
{
get
{
return testStringValue;
} set
{
testStringValue = value;
}
}
}

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>

The code-behind should look something like this:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
TestClass1 tc = new TestClass1();
tc.testString = TextBox1.Text;
Label1.Text = tc.testString;
Label2.Visible = true;
}
}

If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.




Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!
Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!