R – Using Validation controls with a GridView

asp.netgridview

A typical situation:

In my GridView control, I have a Footer row which contains a Textbox and an "Add" Button. When the button is pushed, the Text entered in the TextBox is added to the grid. I also have a validation control to require that, when the button is pushed, that text has been entered in the TextBox. After a new row is added, the textbox is clear to allow for easy entry of the next item.

The user may also edit the text in previously entered rows by clicking the Edit LinkButton, which puts the row into edit mode. Clicking an Update LinkButton commits the change.

The problem:

When, I click the Update link to commit the changes, if text has not been entered in the Footer row's TextBox (the row used to add a new entry), the validation control returns a "Entry Required" error. It should only require an entry if the Add button is pushed, not if the Update LinkButton is pushed.

It seems that the server side Validation control's validating event fires before the GridView's RowCommand event or the btnAdd_Click event, so I am wondering how, from the server, I can determine what event fired the postback so I can determine whether what edits should be performed for the given situation.

I am using a mix of client side "required" validation edits as well as more complex server sides. Since I probably have to have some server sided validations, I would be happy with just knowing how to handle server sided validations, but really, know how to handle this situation for client validations would also be helpful.

Thanks.

Best Answer

Convert your CommandField into a TemplateField, and in the EditItemTemplate, change the Update LinkButton's CausesValidation property to false.

Update:

Converting to a TemplateField is simple and doesn't require any code changes (just markup):

alt text

Changing the CausesValidation property to false in the markup is also straightforward:

<asp:TemplateField ShowHeader="False">
  <EditItemTemplate>
    <asp:LinkButton ID="lnkUpdate" runat="server" CausesValidation="False"
      CommandName="Update" Text="Update"></asp:LinkButton>
    <%--
      More controls
    --%>
  </EditItemTemplate>
  <ItemTemplate>
    <%--
      Controls
    --%>
  </ItemTemplate>
</asp:TemplateField>

Now, if you want your footer and data rows to be validated separately, you need to use validation groups, which is explained in Microsoft's documentation. All the controls in the same validation group will have their ValidationGroup property set to the same value, like this:

<asp:LinkButton ID="lnkUpdate" runat="server" CausesValidation="True"
  CommandName="Update" Text="Update" ValidationGroup="GridViewDataRowGroup">
</asp:LinkButton>
Related Topic