This is how my code looks like.
I want to kno why is the value in the label coming as blank or null.
I want to assign the value to username at get data and use it at the button click event.
Can some1 guide me with this and why is it happening and how to solve this issue
I don’t want to use a session and static.
namespace GUI
{
public partial class Updatechild : System.Web.UI.Page
{
string UserName;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//CALL A FUNCTION TO GET THE VALUE
GetData();
}
}
protected void GetData()
{
//VALUE assigned
UserName= "USER1"
}
// button click event
protected void Button_Click(object sender, EventArgs e)
{
Label.Text = UserName; //value comes as blank.
}
}
To answer the question of why this is happening: Basically each time the server handles a request from the browser for that page, the ASP.NET framework creates a new instance of your
UpdateChildclass.In your scenario there are 2 separate requests happening: one when the page loads for the first time and another when the user clicks the button.
During the first request, since the request is not a postback, your
UpdateChildclass assigns a value to theUserNamevariable. However, since that instance ofUpdateChildwill be discarded once the request is done processing, the value assigned to that variable is lost. If you want to preserve this value, then you’ll need to store it somewhere other than a class-level variable on your page. The most logical place would probably be in either ViewState or Session.A simple solution to your problem is to change the declaration of
UserNameto something like the following: