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
}
If your code is reliant on the OnClick event, then you can put that particular code in the OnPageRender override (rather than in Page_Load), as it will fire after the OnClick event handler.
Page_Load is a handler for the Load event (which is automatically wired-up) and will therefore be invoked as a result of the Load event that's being raised.
Load. The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
The Click event is raised when the Button control is clicked. This event is commonly used when no command name is associated with the Button control (for instance, with a Submit button). Raising an event invokes the event handler through a delegate.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With