HOY
HOY

Reputation: 1007

Prevent onclick within another onclick of the same control

I have a button with an onclick event

<asp:Button ID="btn_Save" runat="server" Text="Save" OnClick="btn_Save_Click"/>

I have a second onclick event for this button as it can be seen in below.

((Button)btn).Click += new EventHandler(SaveClicked);

I debugged and saw that the first one occurs before the second one,

I want to cancel the second onclick from the first one.

Why do I need 2 click events: I have a webcontrol (BulkEditGridView), which takes a Button control as parameter, and this control saves whole rows. Second click event acts as save whole table. Now I added some fields to my webcontrol and I want to prevent saving when button is clicked. Since I can not modify the webcontrols eventhandler (second click event), I added the first onclick event. What I am tring to do is, prevent saving of the gridview, if one of the fields (ex: a textbox field) is empty, which can be done by prevent the default click event.

Upvotes: 0

Views: 193

Answers (3)

HOY
HOY

Reputation: 1007

Session variable can be used .

Upvotes: 0

Yograj Gupta
Yograj Gupta

Reputation: 9869

Just remove second event handler from button click event.

((Button)btn).Click -= new EventHandler(SaveClicked);

but when you not required second event handler, why are you adding that?

You can remove event handler by reflection also, you can try this code, but not tested.

BindingFlags AllBindings = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;

List<FieldInfo> lst = new List<FieldInfo>();

foreach (EventInfo ei in btn.GetType().GetEvents(AllBindings))
{
    Type dt = ei.DeclaringType;
    FieldInfo fi = dt.GetField(ei.Name, AllBindings);
    if (fi != null)
        lst.Add(fi);
}

foreach (FieldInfo fi in lst)
{
    EventInfo ei = btn.GetType().GetEvent(fi.Name, AllBindings);
    if (ei != null)
    {
        object val = fi.GetValue(btn);
        Delegate mdel = (val as Delegate);
        if (mdel != null)
        {
            foreach (Delegate del in mdel.GetInvocationList())
                ei.RemoveEventHandler(btn, del);
        }
    }
}

It will remove all event handler. for more info you can check this link http://www.codeproject.com/Articles/103542/Removing-Event-Handlers-using-Reflection

Upvotes: 2

VIRA
VIRA

Reputation: 1504

I dont know whether i have understood your query correctly.

Remove first method using -= and then add your second method and then again add first method.

So, you will get first executed your second method.

Again, not sure

Upvotes: 0

Related Questions