ViewState value not being retained during postback - c#

How can I make this piece of code work? I am dealing with a bigger issue but if I can make this work then I will know what to do.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Response.Write(ViewState["Value"].ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["Value"] = "Button clicked";
}

Page_Load event happens before Button1_Click and hence you wont be able to access a value that is not already set.
You will need to use an event that happens after Button1_Click like Page_PreRender as you have used in the answer.
Please go through this link to understand Page Life Cycle, which is invaluable in Asp.Net Webforms development.

I was able to solve my problem by putting my logic in pageLoad method in the page_PreRender method like this:
protected void Page_PreRender(object sender,EventArgs e)
{
if (IsPostBack)
{
Response.Write(ViewState["Value"].ToString());
}
}

Related

C# how to stop a control's event

I have an .aspx page that has a page_load as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.Name != "")
{
....
}
else
{
FormsAuthentication.RedirectToLoginPage();
return;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
....
}
The issue I am noticing is that when the user clicks the submit button it goes though the Page_Load (goes though the else) and then tries to run though the protected void btnSubmit_Click(object sender, EventArgs e).
Is there a way to make it redirect to the login page and not continue to the next void?
This is NOT an issue. This is the normal ASP.NET Page Life Cycle.
Controls events fire right after the Page_Load event.
Note that the FormsAuthentication.RedirectToLoginPage method does not end the request by calling HttpResponse.End. This means that code that follows the RedirectToLoginPage method call will run.
Assuming you want to stop further processing from within the Page_Load (which I believe is your intention with return):
protected void Page_Load(Object sender, EventArgs e)
{
if (/*I want to kill processing*/)
{
// Method one:
Response.End(); // Though admittedly ugly
// Method two:
this.Context.ApplicationInstance.CompleteRequest();
return; // return as normal (short-circuit)
}
}

Calling pageload after some operation

I have an aspx.cs file with the following code
protected void Page_Load(object sender, EventArgs e)
{
//Some code
}
protected void Removeabc(object sender, EventArgs e)
{
//Some code
}
In the last line of Removeabc i want to reload the page and call Page_Load again. Please help me on how to do the same.
To reload the page, use
Response.Redirect(Request.Url.ToString())
It will call the Page_Load on that reload.
You can use
Response.Redirect(Request.RawUrl);
It will redirect you to the same page and call Page_Load().
You should wrap that logic into a third method which can be called from both handlers:
protected void Page_Load(object sender, EventArgs e)
{
//Some code
DoSomeCleverStuff();
}
protected void Removeabc(object sender, EventArgs e)
{
//Some code
DoSomeCleverStuff();
}
private void DoSomeCleverStuff() {
// Clever stuff
}
It is good practice not to put heavy logic/code into event handlers in C#. Extract the core logic out into either another method or class so that the code can be re-used elsewhere throughout the class/application.
You can redirect to this page using Response.Redirect(Request.Url.ToString()) or if you only want the code in Page_Load to execute you can call Page_Load(null,null)

Buttonclick and postback issue

Below is a code wherein I want to display a message if there is a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Response.Write("Hidden value :" + HiddenField1.Value);
}
}
protected void btn_Click(object sender, EventArgs e)
{
HiddenField1.Value = "test";
}
The issue is I get the message on clicking the button twice, that is clearly because Page_Load happens before btn_Click. Can anyone suggest me a way wherein I can get the message to be displayed in if (Page.IsPostBack) on page postback?
Kindly help
Yep, you're running into a page life cycle issue. Page_Load happens before any postback events.
If you're just doing Response.Write to the resposne stream, you could move this code to the overriden PreRender event on the page.
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Page.IsPostBack)
{
Response.Write("Hidden value :" + HiddenField1.Value);
}
}

onclick second click

New to asp.net, I am having a problem on a website I am creating, I am using a master page to build my pages. I am trying to change the css class of a li tag using the onclick event in linkbuttons:
<asp:LinkButton runat="server" id="AboutButton" OnClick="about_click" PostBackUrl="about.aspx"><span>About</span></asp:LinkButton>
This linkbutton calls a function in the master page's code behind:
protected void about_click(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
about.Attributes.Add`enter code here`("class", "current");
}
}
This only works when the page is loaded and the button is clicked again. Any help would be greatly appreciated.
By adding: if(Page.IsPostBack) you're specifically telling it not to execute that code the first time the page is loaded, but you want it to happen when the page is first loaded, by the sounds of the question.
Why did you add if(Page.IsPostBack). Try this
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
about.Attributes.Add("class", "current"); //initial setting here
}
}
protected void about_click(object sender, EventArgs e)
{
about.Attributes.Add("class", "current");
}

Only add items to a dropdown list once

I have a dropdown list that is populated when the page loads, like this:
protected void Page_Load(object sender, EventArgs e)
{
ddlCars.Items.Add("Ford");
ddlCars.Items.Add("Chevy");
ddlCars.Items.Add("BMW");
ddlCars.Items.Add("Jeep");
ddlCars.Items.Add("Nissan");
}
It works fine, but when a user changes the selection of the dropdown list, the list is repopulated and I see the same items twice, because the page is reloading and these values are being re-added.
What would be the best way to stop this from happening? It is important that AutoPostBack stays enabled, so that I change information based on user selection.
Thanks
You need to put that code in a !Page.IsPostBack block.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ddlCars.Items.Add("Ford");
ddlCars.Items.Add("Chevy");
ddlCars.Items.Add("BMW");
ddlCars.Items.Add("Jeep");
ddlCars.Items.Add("Nissan");
}
}
This will allow that code to run once (when the page loads the first time), and then be ignored whenever the page is posting back to the server due to user interaction, etc.
For more information, see Page.IsPostBack on MSDN.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
ddlCars.Items.Add("Ford");
ddlCars.Items.Add("Chevy");
ddlCars.Items.Add("BMW");
ddlCars.Items.Add("Jeep");
ddlCars.Items.Add("Nissan");
//ddlCars.datasource=?
//ddlCars.databind();
}
}

Categories