HEEN
HEEN

Reputation: 4721

On Button Click checkbox checked validation in C#

I have a scenario, where I display data in a Gridview. Now what I want is, There are two buttons as Approve and Reject. I want to validate that atleast one checkbox should be checked before clicking on one of the buttons.

Below is my HTML.

<asp:GridView ID="grdDisplayCMMData" runat="server" AutoGenerateColumns="false" Width="100%" ShowHeaderWhenEmpty="true" CssClass="heavyTable table" EmptyDataText="No records to display"
    AllowPaging="true" PageSize="20" OnPageIndexChanging="grdDisplayCMMData_PageIndexChanging">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="Id" ItemStyle-Width="10%" />
        <asp:BoundField DataField="SAP_ID" HeaderText="Sap Id" ItemStyle-Width="10%" />
        <%--<asp:BoundField DataField="ID_OD" HeaderText="ID to OD" ItemStyle-Width="10%" />--%>
        <asp:BoundField DataField="ID_OD_COUNTCHANGE" HeaderText="ID to OD Change" ItemStyle-Width="10%" />
        <asp:BoundField DataField="ID_OD_CHANGEDDATE" HeaderText="ID to OD Change Date" ItemStyle-Width="10%" />
        <asp:BoundField DataField="RRH_COUNTCHANGE" HeaderText="RRH Count Change" ItemStyle-Width="10%" />
        <asp:BoundField DataField="RRH_CHANGEDDATE" HeaderText="RRH Count Change Date" ItemStyle-Width="10%" />
        <asp:BoundField DataField="TENANCY_COUNTCHANGE" HeaderText="Tenancy Count Change" ItemStyle-Width="10%" />
        <asp:BoundField DataField="TENANCY_CHANGEDDATE" HeaderText="Tenancy Changed Date" ItemStyle-Width="10%" />
        <asp:BoundField DataField="STATUS" HeaderText="Current Status" ItemStyle-Width="20%" />

        <asp:TemplateField HeaderText="Approve/Reject">
            <ItemTemplate>
                <asp:CheckBox ID="chkApprRejCMM" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<div class="text-center">
    <asp:Button ID="btnApproveCMM" Text="Approve" runat="server" OnClick="btnApproveCMM_Click" CssClass="btn btn-primary" />
    <asp:Button ID="btnRejectCMM" Text="Reject" runat="server" OnClick="btnRejectCMM_Click" CssClass="btn btn-primary" />
</div>

Also see my OnClick event of Approve.

protected void btnApproveCMM_Click(object sender, EventArgs e)
{
    try
    {
        IPColoFields ObjIPColoFields = new App_Code.IPColoFields();
        List<IPColoBilling.App_Code.UMS.UMSGroupDetails> UMSGroupDetails = (List<IPColoBilling.App_Code.UMS.UMSGroupDetails>)Session["lstUMSGroupDetails"];

        Session["lstUMSGroupDetails"] = UMSGroupDetails;
        string strApprove = "";

        foreach (GridViewRow gvrow in grdDisplayCMMData.Rows)
        {
            var checkbox = gvrow.FindControl("chkApprRejCMM") as CheckBox;

                if (checkbox.Checked)
                {
                    int Id = Convert.ToInt32(grdDisplayCMMData.Rows[gvrow.RowIndex].Cells[0].Text);

                    ObjIPColoFields.Unique_Id = Id;
                    ObjIPColoFields.UMS_GRP_BY_ID = intCurrentGrpId;
                    ObjIPColoFields.UMS_GRP_BY_NAME = strCurrentGrp;
                    ObjIPColoFields.UMS_GRP_TO_ID = UMSGroupDetails[1].GroupID;
                    ObjIPColoFields.UMS_GRP_TO_NAME = UMSGroupDetails[1].GroupName;
                    ObjIPColoFields.FCA_STATUS = "1";
                    ObjIPColoFields.LAST_UPDATED_BY = lblUserName.Text;
                    strApprove = CommonDB.Approve_IPCOLO_CMMLevel(ObjIPColoFields);
                }                                                         
         }
        ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record Approved successfully'); window.location ='IpColoDefault.aspx';", true);
        BindCMMData();
    }
    catch (Exception ex)
    {
        string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
        CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["IPCOLO_LOG"].ToString());
    }
}

I tried the logic of getting the count of checkbox and if it is less than 0 then prompt an error. But in Checkbox there is no such property of getting the count.

Please suggest any other way

Upvotes: 0

Views: 1626

Answers (2)

Sagar Shirke
Sagar Shirke

Reputation: 686

You can follow below steps.

  1. Add some random classname as "XYZ" to your Checkbox

<asp:CheckBox ID="chkApprRejCMM" runat="server" Class="xyz" />

2.add OnClientClick event to button

> <asp:Button ID="btnApproveCMM" Text="Approve" runat="server"
> OnClick="btnApproveCMM_Click" CssClass="btn btn-primary" OnClientClick
> = "javascript:return CheckData(); " />

3.Using Jquery check whether atleast one checkbox is checked and return false if non is sleected inside CheckData function.

`

` if($('input.xyz:checked').length >0) {return false;} else return true;

`

` If function returns false then postback will not happen.

Upvotes: 0

VDWWD
VDWWD

Reputation: 35514

You can do this with a CustomValidator.

<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="countCheckBoxes" 
    ErrorMessage="Check at least one"></asp:CustomValidator>

And then the function to test if there are any checkboxes checked.

<script type="text/javascript">
    function countCheckBoxes(oSrc, args) {
        var cnt = $('<%# GridView1.ClientID %> input[type=checkbox]:checked').length;
        args.IsValid = cnt > 0;
    }
</script>

Upvotes: 1

Related Questions