Is there any way to update the ViewState from a page event (such as a button click) BEFORE the Load event of the page?
I understand that the event handlers only get called after the load events, but is there any way around this?
Due to the life-cycle of an ASP .net page. The only way to pass state to the server that can be accessed OnPageLoad is by using a HiddenField on the page which is updated on the client-side with Javascript.
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["val"] != null)
{
int s = Convert.ToInt32(ViewState["val"]);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["val"] != null)
{
int s = Convert.ToInt32(ViewState["val"]);
s = s + 5;
ViewState["val"] = s;
}
else
{
ViewState["val"] = 6;
}
}
This is the code i tested on my machine
and on page load i am getting the updaetd value each time,
Related
I have a button whose text (a counter on datatable) should be changed when I click Update or Add button.
But it doesn't. It only does when I refresh the page only, why ?
Button are within UpdatePanel.
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = ShowLastHearingDates();
if (dt.Rows.Count > 0)
{
btnShowLasthearingDates.Text = dt.Rows.Count.ToString();
}
update:
protected void btnupdate_click(object sender, Eventargs e)
{
if (MngCaseHearings.UpdateCaseANDHearingDetails(CaseNo, CaseTitle))
{
btnUpdate.Visible = false;
btnAddCaseAndHearingDetails.Visible = true;
}
}
Problem is that the page load event happens before your update occurs. You can put the code in the page prerender event which will be hit after the page load and control event
try to put UpdateMode to "always"
or put all related control in the samne panal
or put AsyncPostBackTrigger
this urls my help
https://msdn.microsoft.com/en-us/library/bb386454.aspx
http://code.runnable.com/UhmIdrdIZy9aAATR/how-to-use-updatepanel-in-asp-net
I have a web page which is contained a Data Filter and a report.The Data Filter is a user control. The report is loaded inside the main page so totally i have two pages. one user control and one web page.
Now i am going to gather the data by clicking a button inside the user control then i can use it to filter the table, but it seems that during the post back it goes first to the Page_Load method of the main, not the user control so the report is constructed before filtering.The BtnPreviewReport_Click must be executed earlier than the page_Load.
What should i do ?
User control
protected void BtnPreviewReport_Click(object sender, EventArgs e)
{
Date = Year.Text + "/" + Month.Text + "/" + Day.Text;
}
Main Page
protected void Page_Load(object sender, EventArgs e)
{
string date = UserControls1.Date;
Response.Write(date);
}
Output : Nothing
I am not sure why the ButtonClick event should be run earlier than page load.
But here's a simple way to solve your question:
private bool isPageLoaded = false;
private bool isButtonClicked = false;
private void ButtonClick()
{
isButtonClicked = true;
doTheFirstThing();
if( isPageLoaded )
{
doTheSecondThing();
}
}
private void PageLoad()
{
isPageLoaded = true;
if( isButtonClicked )
{
doTheSecondThing();
}
// else let the button click handle the SecondThing()
}
I have session variable that dont update with new value. I have two pages, one were you enter the values and klick on the button and you get redirected to page 2 and there you can check your input, if this is wrong you click back-button and you go back to the first page where you can change the input but now when i click the button to validate again the new value does not show up in the session variable but only the old value. I have been readingabout session for the last day but i just cant find the problem, the behind code is below:
Page1
protected void Page_Load(object sender, EventArgs e)
{
if (this.Session["value1"] != null)
{
lbl1.Text = (String)this.Session["value1"].ToString();
}
}
public string info { get { return lbl1.Text; } }
protected void inputButton_onclick(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
Session["value1"] = info;
Response.Redirect("~/validpage.aspx");
}
}
Page 2
protected void Page_Load(object sender, EventArgs e)
{
if (Session["value1"] != null)
{
lbl2.Text = (String)Session["value1"].ToString();
}
}
protected void BackButton_Click(object sender, EventArgs e)
{
Session["value1"] = lbl2.Text;
Response.Redirect("~/Default.aspx");
}
Maybe i have staired my self blind on this code as to me this should not have this problem it is presenting. Any idea and help will be appreciated.
Every time Page1 loads, lbl1 is set to the contents of the session, unless it's never been set. So when you click the button, the lbl1 is first set back to the content of the session as the page is loaded. You then read this value back & but it back in the session.
try this instead:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback)
{
if (this.Session["value1"] != null)
{
lbl1.Text = (String)this.Session["value1"].ToString();
}
}
}
This says only set the value if we're not postback, ie NOT clicking a button on the page.
Also in page2, there's no need to call ToString AND cast to a string. Do either, not both.
I have a table with all the objects I have in my db. I load them in my Page_Load function. I have a text field and a button that when clicking the button, I want the handler of that click to put a new object with the name written in the text field in the db.
Now, I want that what happens after the click is that the page loads again with the new item in the table. The problem is that the button event handler is run after the Page_Load function.
A solution to this would be to use IsPostBack in the Page_Load or use the pre load function. A problem is that if I would have 3 different buttons, I would have to differ between them there instead of having 3 different convenient functions.
Any solutions that don't have this problem?
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
// LOAD DATA FROM DB
}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
}
Maybe you should try loading your data during PreRender instead of Load
protected void Page_Load(object sender, EventArgs e)
{
this.PreRender += Page_PreRender
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
}
protected bool reloadNeeded {get; set;}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
reloadNeeded = true;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if(reloadNeeded || !IsPostBack)
// LOAD DATA FROM DB
}
You can check the event target and do what you need then:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string eventTarget = Page.Request.Params["__EVENTTARGET"];
if(whatever)
{
//do your logic here
}
}
}
Get control name in Page_Load event which make the post back
Use the Page_PreRenderComplete event to retrieve your table. That way your page will always have the most recent data available after all user events have fired.
Why don't you move what you have in the click event into a new method. Then call that method as the first line in your page load?
An old question but I faced the same problem in my C#/ASP.NET Website with master/content pages: a click on a link on the master page should change a query parameter for a gridview on the content page. As you stated the button click event is handled after Page_Load. But it is handled before Page_LoadComplete (see the information about ASP.NET Page Life Cycle), so you can change the page content there.
In my case I solved the problem by setting a session variable in the click event in the master page, getting this variable in the Page_LoadComplete event in the content page and doing databind based on that.
Master page:
<asp:LinkButton ID="Btn1" runat="server" OnCommand="LinkCommand" CommandArgument="1" >Action 1</asp:LinkButton>
<asp:LinkButton ID="Btn2" runat="server" OnCommand="LinkCommand" CommandArgument="2" >Action 2</asp:LinkButton>
protected void LinkCommand(object sender, CommandEventArgs e)
{
HttpContext.Current.Session["BindInfo", e.CommandArgument.ToString());
}
Content page:
protected void Page_LoadComplete(object sender, EventArgs e)
{
string BindInfo = HttpContext.Current.Session["BindInfo"].ToString();
YourBindDataFunction(BindInfo);
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // If page loads for first time
{
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); // Assign the Session["update"] with unique value
//=============== Page load code =========================
//============== End of Page load code ===================
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString()) // If page not Refreshed
{
//=============== On click event code =========================
Label1.Text = TextBox1.Text;
//lblDisplayAddedName.Text = txtName.Text;
//=============== End of On click event code ==================
// After the event/ method, again update the session
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else // If Page Refreshed
{
// Do nothing
}
}
protected override void OnPreRender(EventArgs e)
{
ViewState["update"] = Session["update"];
}
}
This is not working for high resolution gradient background.
Consider wrapping your button and the label in an updatepanel control, which uses AJAX to refresh their contents.
The rest of the page will not be reloaded and the action will not affect the browser navigation.
See this page on how an updatepanel control works.
Since you are handling the button click event in server side there has to be a postback to handle it.
If you do not want a post back to happen change the event handling to "client click"
//Heinzi code worked for me just made a small change in OnPreRender event, assign the ViewsState value when its not post back
protected override void OnPreRender(EventArgs e)
{
if (!IsPostBack)
{
ViewState["update"] = Session["update"];
}
}