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"];
}
}
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 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 web form which dynamically loads controls upon selection in combobox(devexpress). I have the following code on main form
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
if (Session["_active_control"] != null)//persist control on postbacks
{
Control cntrl = Session["_active_control"] as Control;
pnl_main.Controls.Clear();
pnl_main.Controls.Add(cntrl);
}
}
protected void cmb_control_SelectedIndexChanged(object sender, EventArgs e)
{
Control cntrl= Page.LoadControl("~/" + cmb_control.SelectedItem.Value);
pnl_main.Controls.Clear();
pnl_main.Controls.Add(cntrl);
Session["_active_control"] = cntrl;
}
also I have a user control having three Textboxes and a button having code
protected void btn_save_Click(object sender, EventArgs e)
{
lbl.Text = ASPxTextBox1.Text + "<br>" + ASPxTextBox2.Text + "<br>" + ASPxTextBox3.Text;
}
My problem is that the save button of user control is not firing if i load it dynamically (I have checked using breakpoints and also the code shown above. however it runs smoothly if I use it statically.(i.e. by dragging in design mode)
You are right that you have to persist the control across postbacks.
However the Page Load event is too late to add back your controls. Do this on the Init event of your page and you should be good. To receive a postback event, the control should be present when ProcessPostData(called before PreLoad) is called.
Also for textboxes you will want to receive the values entered by the user. This too happens on ProcessPostData, if you add you control after that, you will not receive the values entered by the user.
Refer: ASP.NET Page Life Cycle
hey i found the solution
instead on creating the controls in combobox_selectedindexchanged i put my control creation code on Pageload based in combobox.selectedindex i.e.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (cmb_control.SelectedItem != null)
{
Control cntrl = Page.LoadControl("~/" + cmb_control.SelectedItem.Value);
cntrl.ID = "_new_ctrl" + cmb_control.SelectedItem.Value;
pnl_main.Controls.Clear();
pnl_main.Controls.Add(cntrl);
}
}
see Button click event not firing within use control in ASP .Net
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);
}
I have a button on a content page which is suppose to modify the value of a textbox on the master page. The setup is simple enough.
Content Page - Code Behind - Button Click Handler:
protected void but_mybutton_Click(object sender, EventArgs e)
{
string new_value = "!!";
Master.textbox_value(new_value);
}
The problem is that by the time it get to that function, the master's page is already rendered. To get the new value to display, I would need to re-fresh the page. Is there anyway to explicitly tell a page to re-render because I have changed some values on it's controls without having to re-fresh the page?
The master page renders indeed like it's a control on the page.
This blogpost shows you the full page life cycle including the events of the master page.
http://weblogs.asp.net/ricardoperes/archive/2009/03/08/asp-net-page-events-lifecycle.aspx
From the code you have provided this should work as the OnClick handler of the button gets executed before the OnPreRender of the masterpage. Can you show us the code of what
Master.textbox_value(new_value);
does?
I just tested this with the most simple setup. On the masterpage 1 label and a method that sets the text of the label.
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e) {}
public void SetLabelText(string text) {
this.Label1.Text = text;
}
}
On the content page a button. The onclick handler of the button calls the method on the masterpage.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {}
protected void Button1_Click(object sender, EventArgs e)
{
((SiteMaster)this.Master).SetLabelText("foo");
}
}
This sets the text of the label in the same postback as expected.
You will need to review the ASP.NET Page Life Cycle to get a better understanding of how the events are firing.
Your best bet is to try setting the value on the page OnInit or LoadViewstate events.