Hi
I'm trying to reach Label1 in aspx file from another class than the partial class , but i get the error: at the bold line below:
System.NullReferenceException: The object reference is not set to an instance of an object
Yet, i created an instance for Label1. Thansk for help. V.
using System;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
public string a="ok";
protected void Page_Load(object sender, EventArgs e)
{
Test ts = new Test();
ts.Txtch();
}
}
class Test : WebForm1
{
public void Txtch()
{
WebForm1 wb = new WebForm1();
wb.Label1.Text = a;
}
}
}
aspx file
---------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" inherits="WebApplication1.WebForm1" %>
...
...
Designer.cs
-----------
public global::System.Web.UI.WebControls.Label Label1;
Pasang TamangPosted Jan 1, 2023, 8:43 AM
Hi,
Practically, I won't recommend the way you are writing the code. Let me correct a bit. First you are inheriting WebForm1 to your Test class. Then in WebForm1 you are trying to access method from class Test. This is like creating a chain between 2 classes. In class Test you better keep methods, functions or extensions that handles application wide business logic and you can call a central code in different forms. If you already can access both Label1 and TextBox1 in your WebForm1 then just to assign value of TextBox1 to Label1, you don't need to use second class, unless there is business logic that needs separation.
In below code, I have created a function which you can call from WebForm1. When you get result, it gives you some additional text as well.
Regards,
Pasang
Aravind GovindarajPosted Jan 1, 2023, 10:12 AM
For partial class, firstly please load the control in your main page, then consume or assign value, to avoid object reference error.
Please refer how to load control in aspx page...
Sachin SinghPosted Jan 1, 2023, 7:51 AM
Are you even able to build the project without errors?
Web Forms are ancient, there is a reason behind partial pages, the main purpose is, aspx and design and .cs all represent same class, so microsoft find it easy to generate html from design and vise-versa, also as the partial page inherits from System.Web.Ui.Pages it becomes a special class that is no longer oops complient.