views:

415

answers:

2

I currently have a Gridview, and I want to use client-side validation to ensure that a row has been selected (ie: SelectedIndex > -1).

At the moment I'm using <asp:CustomValidator> but want to move away from server-side validation. Here is what I'm currently doing:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField HeaderText="MSN" DataField="MSN" />
        <asp:CommandField ShowSelectButton="True" />
    </Columns>
</asp:GridView>
<asp:CustomValidator ID="cvSelected" runat="server" ErrorMessage="Please select!" />

And then in code behind:

Private Sub cvSelected_ServerValidate(ByVal source As Object, ByVal args As _
System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvSelected.ServerValidate
    args.IsValid = (GridView1.SelectedIndex > -1)
End Sub
A: 

That seems OK to me. Client-side validation in this specific case sounds a little fuzzy, like maybe checking for some element you expect to have part of a server-generated ID. Very fragile.

Usually I will go one extra step and actually create my own validator control which inherits from BaseValidator. Makes encapsulation and SoC cleaner, and the validation logic portable as well.

Rex M
A: 

In the GridView_RowCreated() event of your code behind the page, you can add attributes to the row tag like so:

e.Row.Attributes.Add("onclick", "SetRowSelected();");

Then you need to include the javascript function "SetRowSelected()" in your page, and have it set a Hidden Field (named IsRowSelected, for example) to a value like "true".

Then you can add another javascript function to the "onclick" event of the control used to submit the page - and have it check the value of the hidden control. If it isn't true, just display an alert() to the user - otherwise submit the page.

Does that sound like it will work?

Ron Savage