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.
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)
Then in your WebForm.aspx.cs, you can call
Where txtEmail is the control. You can make the Validate class static, so you can just do: