Tuesday, 26 July 2011

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 used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

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>

Try Server Intellect for Windows Server Hosting. Quality and Quantity!

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;
}
}

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

Looking for more ASP.NET Tutorials? Click Here!

No comments:

Post a Comment