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);
}
Related
In my javascript file, I got an ajax to get all list and iterate these data and append <a id='userID' class='btn'>Assign ID<> to my list.
So, how do a add postback to these anchor and redirect it inside my method in the server. Below is my code but didn't work. When I click the achor button, it just redirect/refresh to the same page without doing any changes and didn't show the text.
<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick='javascript:__doPostBack('uniqueID','')'>Assign ID</a>
protected void Action_assignID(object sender, EventArgs e)
{
// assign ID action
Response.Write("Pass");
}
You should be changed your button to:
<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick="javascript:__doPostBack('uniqueID','Assign ID')">Assign ID</a>
And it's a good idea to implement the IPostBackEventHandler interface in your codebehind as below:
public partial class WebForm : Page, IPostBackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
public void RaisePostBackEvent(string eventArgument)
{
// do somethings at here
}
}
Hope this help!
The __doPostBack method really doesn't do anything special except, well... perform a POST operation back to the same page with two specific form arguments.
The first parameter is the __EVENTTARGET and the second parameter is the __EVENTARGUMENT.
The magic all happens in ASP.Net where it automagically wires up your controls to event handlers, but since you are creating these entirely in JavaScript the server doesn't know that those controls exist.
However, you can manually grab these values and do something with them.
//Client Side JavaScript:
__doPostBack('my-event', '42');
//Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var target = Request.Params["__EVENTTARGET"];
var args = Request.Params["__EVENTARGUMENT"];
Target.Text = target; // 'my-event'
Argument.Text = args; // '42'
}
}
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 created a dropdownlist in my webpage which is outside the gridview and I have added automatic refresh. My problem is that I`m unable to retain the selected value in dropdownlist after the refresh. It goes to the default settings in the dropdown. Please help.
Thanks a lot for replying..
part of my code goes this way....
page_load(...)
{
Refresh
if(!IsPostBack)
{
//calling my function which includes databind..
myfunction();
}
}
i tried the same code as you people suggested but its not working..
even now after refresh, the default values appear in dropdownlist
You probably need to implement something like this in your page_load handler:
if (IsPostback) return;
//here populate the dropdown
Let me guess your Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
DataBindGridView(); // loads the datasource of the grid and calls gridView1.DataBind();
DataBindDropDown(); // loads the datasource of the dropdown and calls dropDown1.DataBind();
}
Do not reload all on every postback, just if !(IsPostBack):
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DataBindGridView();
DataBindDropDown();
}
}
If you need to refresh your GridView don't use Page_Load but the appropriate event handler. If you use an ASP.NET Timer to reload your page periodically to refresh the grid, use it's Tick event.
protected void GridRefreshTimer_Tick(object sender, EventArgs e)
{
DataBindGridView();
}
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"];
}
}
On PostBack, from clicking on an ImageButton, it first hits
protected void Page_Load(object sender, EventArgs e)
Then it hits
protected void ImageButton_Click(object sender, EventArgs e)
My problem is that in my Page_Load it refreshes a ListBox before the selected items can be processed by ImageButton_Click.
Is there a way to tell what events are yet to be processed, so I can handle them?
Populate/databind your ListBox within Page_Load only on the first load, not after postback. Viewstate will maintain the items in your ListBox subsequently.
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) //if not postback
{
//populate your listbox
}
}
Here's a good read on the Page's Lifecycle, you'll understand the sequence/order of page/child-controls' events and their purposes.
http://msdn.microsoft.com/en-us/library/ms178472.aspx