Thursday, April 11, 2013

GridView CheckBox Alert

Scenario :
In GridView,when One checkBox Selected, the Same Row another CheckBox
has to be selected : 
Following is the code:
----------------------
    <asp:GridView ID="Gv1" runat="server" OnRowDataBound="Gv1_OnRowDataBound"
     OnRowCommand="Gv1_OnRowCommand" AutoGenerateColumns="false"> 
     <Columns>
     <asp:TemplateField>
     <ItemTemplate>
     <asp:CheckBox ID="chk1" runat="server" />
     </ItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField>
     <ItemTemplate>
     <asp:Label ID="lblName" runat="server"></asp:Label>
     </ItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField>
     <ItemTemplate>
     <asp:CheckBox ID="chk2" runat="server" />
     </ItemTemplate>
     </asp:TemplateField>
     </Columns>
     </asp:GridView>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="return validate();" />
 
----------------------------------------------------------\
Javascript
------------
<script type="text/javascript">
        function validate() {
            var isValid = false;
            var gridView = document.getElementById('Gv1');
            for (var i = 1; i < gridView.rows.length; i++) {
                var inputs = gridView.rows[i].getElementsByTagName('input');
                if (inputs != null) {
                    if (inputs[1].type == "checkbox") {
                        if (inputs[1].checked) {
                            if (inputs[0].checked == false) {
                                alert("Please select atleast one checkbox");
                            }
                            else {
                                isValid = true;
                                return true;
                            }
                            
                        }
                    }
                }
            }
            alert("Please select atleast one checkbox");
            return false;
        }
    </script>


Output:



-----------



GridView_Image