Create custom base class to reuse code throughout site -- can't seem to get it to work!

R

Ranginald

Hey,

I'm trying to create a simple class to create a textbox, and then
instantiate it from a page (so I can resue it across an asp.net app).
I've been scratching my head but I can't get this to work. I am I in
the right direction?

BaseClass.cs
============
public class BaseClass
{
protected TextBox textBox1;
public BaseClass()
{
}
public void CreateTextBox()
{
TextBox textBox1 = new TextBox();
textBox1.Text = "Hello from BaseClass";
textBox1.EnableViewState = true;

}

Default.aspx
===========
<asp:placeHolder ID="PlaceHolder1" runat="server">

Default.aspx.cs
============
BaseClass sample = new BaseClass;
BaseClass.CreateTextBox();

-------> It all compiles but no textbox appears.

1) How do I "tell" the BaseClass.cs to look for the PlaceHolder1 on the
default.aspx page? I always get a not in the current context problem.

2) And how do I "tell" default.aspx.cs that the textBox1 is the
textbox to use?

Any ideas?

Thanks!
-David
 
K

Karl Seguin [MVP]

If it's actually a base class, your code should look like:

public clas BaseClass : Page
{
blah
}

//default.aspx.cs
public class _Default : BaseClass
{
//blah
}


if all pages that inherit from BaseClass are going to have a placeholder,
you can declare it in your base class, something like:

protected PlaceHolder PlaceHolder1;

Karl
 
R

Ray Booysen

In default.aspx.cs you don't ever set the text box to be displayed
anywhere. Where do you want to place it?

You can expose the textbox1 as a property from BaseClass to allow
default.aspx and other classes to access it.

E.g.

public property TextBox MyTextBox
{
get ( return textBox1; }
set { textBox1 = value; }
}

Then in default.aspx.cs you can access it:

BaseClass _bc = new BaseClass();

_bc.MyTextBox.Text = "Hello World";

Then you can use this property to place it on the form somewhere.
 
R

Ray Booysen

You can then add the control to the placeholder:

PlaceHolder1.Controls.Add(_bc.MyTextBox);

Ray Booysen wrote:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,835
Latest member
lila30

Latest Threads

Top