简体   繁体   中英

Is it possible to cancel a triggered event?

I am developing asp.net web application.In this, for a button click Page_Load event is triggered before the button_click . so my question is that in Is it possible to suspend the button_click event within Page_Load based on some condition.(both c# or Vb.Net solutions are acceptable). Currently i am achieving this by using some flag values as like the following:

Setting a flag value in page load based on some condition

bool buttonFlag = false;
protected void Page_Load(object sender, EventArgs e)
 {
    if (condition) { buttonFlag = true; }
 }

Check the flag value and call the method if flag is true(so action is performed only when the flag value is true.) hence we can skip the action based on the condition set from page load.

protected void Button1_Click(object sender, EventArgs e)
    {
        if (buttonFlag) 
        {//call mymethod
            myMethod();
        }
    }

Is it possible to suspend the event without using a flag?

I suppose you have linked the Button1_Click function to the click event with the standard page desinger in visual studio. If you want the event handler t be active on certain conditions, you will have to bind it more dynamicly.

You first need to remove the function name in the click event box in the page designer.

Then, you can attach it in your page load :

protected void Page_Load(object sender, EventArgs e)
{
    if (condition) { 
        Button1.Click += Button1_Click;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM