Synthel Synthel - 3 years ago 135
ASP.NET (C#) Question

How can I access the controls on my ASP.NET page from a class within the solution?

Basically I am not using a MasterPage and I just have a project with a Default.aspx with a few labels, textBoxes etc. I've spent several hours looking for a solution and I have found one, but something in my head still bugs me, that I didn't do it the way I wanted to.

I have no troubles accessing them and setting their properties from the PageLoad.

But I made a class, just like the code snippet below, and it throws me an "Object reference not set to an instance of an object". And I cannot seem to figure out what I am missing.

class Functions
{
public static void myMethod()
{
WebForm1 mainForm = new WebForm1();
mainForm.myTextBox.Text = "Something.";
}
}


I managed to do with like this:

class Functions
{
public static void myMethod()
{
System.Web.UI.Page myMainForm;
myMainForm = (System.Web.UI.Page)System.Web.HttpContext.Current.Handler;
TextBox myTextBox = (TextBox)myMainForm.FindControl("myTextBox");
}
}


But it's not about just doing it, it's about learning where I am wrong as I cannot figure it out and I want a simpler way to do it, considering I am very new to ASP.NET. Normally when I am coding basic applications in WinForms - I don't have problems accessing different forms.

And I don't like doing a FindControl() for every control I am trying to access. If there is a simple and yet effective workaround I would love to hear it.

Thank you in advance.

Edit: I've made this example aside from my project, but it's the idea I am trying to accomplish. There might be some small errors in the code snippets, please excuse me.

Answer Source

Use the code-behind files for this. Don't tightly couple business logic classes to your user interface.

WebForm1.aspx should have WebForm1.aspx.cs if using c# or WebForm.aspx.vb if using vb, so if you have a TextBox control on WebForm1.aspx, you should be able to access it in the code-behind file (WebForm1.aspx.cs or WebForm1.aspx.vb)

public class Validate
{
    public bool IsEmail(string email)
    {
        //return false if invalid e-mail or true if valid
    }
}

Then in your WebForm.aspx.cs, you can call

 Validate validate = new Validate();
 bool isValidEmail = validate.IsEmail(txtEmail.Text);

Where txtEmail is the control. You can make the Validate class static, so you can just do:

 bool isvalidEmail = Validate.IsEmail(txtEmail.Text);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download