I have the next code.
protected void Page_PreRender(object sender, EventArgs e)
{
bool isDelayWarning = proxy.MerchantPaySystemSetting_IsHoldPaymentsAllow(clientID, PaySystem.Type));
ViewState.Add("IsDelayWarning", isDelayWarning);
}
protected void btnSend_Click(object sender, EventArgs e)
{
if ((bool)ViewState["IsDelayWarning"] && !cbxDelayConfirm.Checked)
{
this.CustomErrorMessage = Yandex_Term_Error;
return;
}
}
In btnSend_Click method ViewState["IsDelayWarning"] = null.
How can I resolve this trouble?
Thanks! :)
I'm not sure about the logic you're going for, but a button push happens during post-back, before the page is rendered. Put breakpoints in your two methods to see their relative order.
Pay attention to the yellow marked items, control event processing is one of them and it happens strictly before PreRender.
You can always check for null reference by doing something like this
if (something != null)
code ------
or another way if you will sometimes have null is to use. For example if user address is null
if (thisuser.Address == null)
{
thisuser.Address = new Address();
}
thisuser.Address = user.Address.City;
Related
I am receiving this error message when I debug my program.
Object reference not set to an instance of an object.
That error happens on this line:
protected void Page_Load(object sender, EventArgs e)
{
bool x = (bool)Session["IsConnectionInfoSet"];--> error here
if (IsPostBack && x)
//do something with the bool x variable
}
Postback is invoked by:
protected void btnDo_Click(object sender, EventArgs e)
{
//do something
Session["IsConnectionInfoSet"] = true;
//do something
}
This error happened in Visual Studio 2008, .NET Framework 3.5.
Can someone give me advice on how this?
The Page_Load method is always run before any event handlers. As a result, the page_load will run, find null and throw an error, all before you click handler has a chance to set this session value.
Here's a safer way to access this session value
bool x = Session["IsConnectionInfoSet"] == null ? false :
(bool)Session["IsConnectionInfoSet"];
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//this is the first time page load.
}
else
{
if (Session["IsConnectionInfoSet"] != null)
{
bool x = (bool)Session["IsConnectionInfoSet"];
if (x)
{
//do something with the bool x variable
}
}
}
}
Hope this helps
I'm using a details view in my asp.net web application.
When it fires its updated and inserted events I'd like to handle them the same way. Because the event args they have are two separate classes with no common inheritance I have to have two separate methods with basically the same code.
Is there any way around this?
eg.
protected void DetailsViewItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
if (e == null)
return;
if (e.Exception != null)
{
e.ExceptionHandled = HandleException(e.Exception);
e.KeepInInsertMode = e.ExceptionHandled;
}
}
protected void DetailsViewItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
if (e == null)
return;
if (e.Exception != null)
{
e.ExceptionHandled = HandleException(e.Exception);
e.KeepInEditMode = e.ExceptionHandled;
}
}
I'd like to extract
if (e == null)
return;
if (e.Exception != null)
{
e.ExceptionHandled = HandleException(e.Exception);
e.KeepInEditMode = e.ExceptionHandled;
}
into some kind of common method if possible.
I agree it is disappointing that these classes inherit directly from EventArgs. It seems logical that they would inherit from the same sublass of EventArgs given not just their common properties, but the fact that most times you use a DetailsView for inserting you also use it for updating.
That being said, what you want to do can be accomplished with a bit of dynamic C#. It's pretty cool, and maybe even a little elegant, albeit a little more overhead.
Try this: (requires C# 4.0)
protected void DetailsView1_Inserted(Object sender, DetailsViewInsertedEventArgs e)
{
ProcessDetailsViewEventArgs(e);
}
protected void DetailsView1_Updated(Object sender, DetailsViewUpdatedEventArgs e)
{
ProcessDetailsViewEventArgs(e);
}
private void ProcessDetailsViewEventArgs(dynamic e)
{
if (e == null)
return;
if (e.Exception != null)
{
e.ExceptionHandled = HandleException(e.Exception);
e.KeepInEditMode = e.ExceptionHandled;
}
}
Use the OnItemCommand, & give your Edit & Delete buttons CommandNames. This event will handle both scenarios for you.
I am building an ASP.NET custom server control.
I have implemented both the IPostBackDataHandler and IPostBackEventHandler.
OnPreRender I have registered the postback logic:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Page != null)
{
Page.RegisterRequiresRaiseEvent(this);
Page.RegisterRequiresPostBack(this);
}
}
The control uses a ImageButton (but I have also tried with a simple Button); when it is clicked I can see the page "refreshes", and some data are posted (I checked that).
However, I don't know why the RaisePostBackEvent(string eventArguments) is not firing.
Does anyone know what's going on? Could someone point me to the right direction to solve this?
Thanks in advance,
Cheers,
Gianluca.
Registering your control during PreRender phase is too late. You can do it during the Load phase instead:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (Page != null && Page.IsPostBack)
{
Page.RegisterRequiresRaiseEvent(this);
Page.RegisterRequiresPostBack(this);
}
}
I have a page Product.aspx,there I have a user control ProductDisplay.ascx which has been created by drag and drop.
Now when a button is clicked in ProductDisplay.ascx,I want a logging function to be called which is in Product.aspx.
To achieve this I have used delegates
on ProductDisplay.ascx
public delegate void LogUserActivity(ProductService objService);
public event LogUserActivity ActivityLog;
on Product.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ProductDisp.ActivityLog += new User_UserControl_ProductDisplayBox.LogUserActivity(LogProduct);
}
}
Now button click event of ProductDisplay.ascx
protected void imgBtnBuyNow_Click(object sender, ImageClickEventArgs e)
{
if (ActivityLog != null)
{
ActivityLog(Product);
}
Response.Redirect("~/User/ShoppingCart.aspx");
}
My problem is that whenever i click this button ActivityLog is null.Why is it null?
My idea is that once i click this button,page posts back and its previous state is lost.
Please help me out with a reason and solution.
Secondly,I want to do away with null checking
**if (ActivityLog != null)**
{
ActivityLog(Product);
}
I saw some code which instantiates a delegate with a default value the moment it is declared,but i was not able to find it.Please help.
I have found solution to first problem
if (!IsPostBack)
{
ProductDisp.ActivityLog += new User_UserControl_ProductDisplayBox.LogUserActivity(LogProduct);
}
This was causing the issue.Move this line
ProductDisp.ActivityLog += new User_UserControl_ProductDisplayBox.LogUserActivity(LogProduct);
out of if (!IsPostBack)
Duplicate of Asp.Net Button Event on refresh fires again??? GUID?
hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again.
any one know some method to prevent page refresh with out redirect the page to the same page again ?
something like if (page.isRefresh) or something... or if exist any javascript solution is better.
this seen to works.... but when i refresh it does not postback but show the before value in the textbox
http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx
private Boolean IsPageRefresh = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
TextBox1.Text = "Hi";
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!IsPageRefresh) // check that page is not refreshed by browser.
{
TextBox2.Text = TextBox1.Text + "#";
}
}
Thanks for comments and sorry for my mistake,
I found this code in:
http://www.codeproject.com/KB/aspnet/Detecting_Refresh.aspx
And this time tested ;)
private bool _refreshState;
private bool _isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
_refreshState = bool.Parse(AllStates[1].ToString());
_isRefresh = _refreshState == bool.Parse(Session["__ISREFRESH"].ToString());
}
protected override object SaveViewState()
{
Session["__ISREFRESH"] = _refreshState;
object[] AllStates = new object[2];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(_refreshState);
return AllStates;
}
protected void btn_Click(object sender, EventArgs e)
{
if (!_isRefresh)
Response.Write(DateTime.Now.Millisecond.ToString());
}
You can test for the Page.IsPostBack property to see if the page is responding to an initial request or if it's handling a PostBack such as your button click event. Here's a bit more information: w3schools on IsPostBack
Unfortunately that's not going to solve your problem since IsPostBack will be true when the user clicks the button as well as when they refresh the page after the button action has taken place.
If you're doing a task like performing CRUD on some data, you can Response.Redirect the user back to the same page when you're done processing and get around this problem. It has the side benefit of reloading your content (assuming you added a record to the DB it would now show in the page...) and prevents the refresh problem behavior. The only caveat is they still resubmit the form by going back in their history.
Postbacks were a bad implementation choice for the Asp.net and generally are what ruin the Webforms platform for me.
This doesn't solve the problem.
First of all, storing a token in the view state is not a good idea, since it can be disabled. Use control state instead. Although, a HttpModule is a better solution.
All in all, this will not work anyway. If you open another tab/window the session will be invalid for the previous tab/window. Therefore braking it. You must somehow store a unique value each time a page is first loaded. Use that to determine where the request came from and then check the "refresh ticket". As you may see, the object for one user might get pretty big depending on the amount of requests made, where and how long you store this information.
I haven't seen any solution to this I'm afraid, as it is pretty complex.
bool IsPageRefresh ;
if (Page.IsPostBack)
{
if (ViewState["postid"].ToString() != Session["postid"].ToString())
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postid"] = Session["postid"];
I tried many ways and I ended up looking for the form data sent when the postback / refresh is triggered... I found that there is a Key for any VIEWSTATE created and you can just compare those Keys like...
I put that on my custom basepage to reuse it like an Property
public bool IsPageRefresh = false;
protected void Page_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
var rForm = Request.Form;
var vw = rForm["__EVENTVALIDATION"].ToString();
var svw = Session["__EVENTVALIDATION"] ?? "";
if (vw.Equals(svw)) IsPageRefresh = true;
Session["__EVENTVALIDATION"] = vw;
}
}