Search code examples
asp.netgridviewevent-handlingmaster-pages

Button in GridView, OnCommand, Event Bubbling, Master Page


Prerequisite, I am fairly new to event bubbling.

I have a page with a gridview that has buttons in the rows. When the button is clicked, it fires an OnCommand event and everything works as expected.

<ItemTemplate>
    <asp:Button ID="btnG" runat="server" OnCommand="btnG_Command" Text="View"/>
</ItemTemplate>

... (on the codebehind) .. 

Protected Sub btnG_Command(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
    'Does some stuff

When I added a textbox (with validators) and a button on the Master Page, now when the buttons in the gridview are clicked, it fires the validators in the Master page for some reason.

<asp:RequiredFieldValidator ID="ReqValidator" runat="server" ControlToValidate="txtTextbox" Display="Dynamic" ErrorMessage="Please enter a valid number."></asp:RequiredFieldValidator>

Through some research I found that it has to do with event bubbling somehow since the button controls in the gridview are using OnCommand rather than OnClick.

My question is why is it firing the validators off in the Master page? Shouldn't the bubbling first go through the GridView instead of the Master page? How can I bypass the validators or event bubbling so that the correct event is fired from the content page?


Solution

  • You should add a validation group to your validator in the master page. Validation groups allow you to organize validation controls on a page as a set. Each validation group can perform validation independently from other validation groups on the page.

    You create a validation group by setting the ValidationGroup property to the same name (a string) for all the controls you want to group. You can assign any name to a validation group, but you must use the same name for all members of the group

    Source: https://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx

    <asp:RequiredFieldValidator ID="ReqValidator" runat="server" 
       ControlToValidate="txtTextbox" Display="Dynamic"
       ErrorMessage="Please enter a valid number." 
       ValidationGroup="MasterNumber"></asp:requiredfieldvalidator>