Thursday, October 30, 2014

Validating CheckBox Selected or Not In Gridview Before Submitting Page.

Validating CheckBox ie Selected Or Not in Gridview before submitting page and if not showing alert message to user using javascript.

In Default.aspx

In <body> tag

<form id="form1" runat="server"> 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"> 
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:BoundField DataField="StateID" HeaderText="StateID" SortExpression="StateID" /> <asp:BoundField DataField="CountryID" HeaderText="CountryID" SortExpression="CountryID" /> <asp:BoundField DataField="StateName" HeaderText="StateName" SortExpression="StateName" /> 
<br /> 
<asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="javascript:return ValidateCheckBox();" /> 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ExampleConnectionString %>" SelectCommand="SELECT * FROM [StateMaster] ></asp:SqlDataSource> </div> </form>

I created gridview with one checkbox column in that and one Button control and i binded gridview with SqlDataSoure property .

After that i created JavaScript Function to validate checkBox Selected or Not in GridView
Place below Javascript in <head> tag as shown in below.

<head runat="server">
    <script type= "text/javascript">
        function ValidateCheckBox() {
            var count = 0;
            var gridview = document.getElementById('<%= GridView1.ClientID %>');
            /*Get all the controls from gridview*/
            for (var i = 0; i < gridview.getElementsByTagName("input").length; i++) {
                /*Get the type of control like input*/
                var chknode = gridview.getElementsByTagName("input")[i];
                /*Check weather checkbox is selected or not*/
                if (chknode != null && chknode.type == "checkbox" && chknode.checked) {
                    count = count + 1;
            /*Alert message if none of the checkboc is selected*/
            if (count == 0) {
                alert("Select one checkbox atleast from gridview.");
                return false;
            else {
                return true;


After That execute the application you will get following output


No comments:

Post a Comment