Friday, November 27, 2015

How to enable required field validator in a particular row of GridView?

Scenario:
In some cases editing is enabled on the selected row when you doing batch editing in ASP.NET GridView or DevExpress Grid Control. During edit operation we need to validate only these selected rows editor controls so that it will not block or validated another rows. It require to enable only associated cell validators in the editing rows.
Solution:
Let we have a checkbox in each row to select the editing row to enable the validator controls. Then we have to follow below steps:
First you need to add server event on Check Box control of Change event fire.
<asp:CheckBox ID="chkbox" runat="server" OnCheckedChanged="chkbox_CheckedChanged"    AutoPostBack="true"/>


Then fire of checked event of Checkbox you need to enable/disable RequiredFieldValidator server control.

protected void chkbox_CheckedChanged(object sender, EventArgs e)
{
   CheckBox chkbox= sender as CheckBox;
   GridViewRow currentRow = chkbox.NamingContainer as GridViewRow;
   RequiredFieldValidator rfv = grdCustomer.Rows[currentRow.RowIndex]
                                      .FindControl("ValReqED") as RequiredFieldValidator;
   if (chkCustomer.Checked)
   {
      rfv .Enabled = true;
   }
}

ASPX:

<asp:GridView ID="grdView" AutoGenerateColumns="false" BorderWidth="0" OnRowCommand="grdView_RowCommand" runat="server" CssClass="table">
    <Columns>
        <asp:TemplateField HeaderText="Save It">
            <ItemTemplate>
                <asp:CheckBox ID="chkbox" runat="server" AutoPostBack="true" OnCheckedChanged="chkbox_CheckedChanged"/>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Expiration Date">
            <ItemTemplate>
                <asp:TextBox ID="txtExpirationDate" style="padding:12px 5px;" placeholder="(mm/dd/yyyy)" CssClass="datepiker" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="ValReqExpD" Enabled="false" Display="Dynamic" runat="server" ErrorMessage="Expiry Date cannot be Blank." ControlToValidate="txtExpirationDate"></asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator Display="Dynamic" ID="ValRegExpD" runat="server" ControlToValidate="txtExpirationDate" ErrorMessage="Enter a valid Expiry Date ." ValidationExpression="([1-9]|0[1-9]|1[012])([-/.])([1-9]|0[1-9]|[12][0-9]|3[01])([-/.])(19[5-9][0-9]|20[0-4][0-9])">
                    <b>Enter a valid Renewal Date</b>
                </asp:RegularExpressionValidator><br />
                <asp:CompareValidator ID="ValCmpSD" Display="Dynamic" runat="server" ControlToCompare="txtEffectiveDate" ControlToValidate="txtExpirationDate" ErrorMessage="Expiry Date should be greater than Effective date" Operator="GreaterThan" Type="Date"></asp:CompareValidator>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>



No comments :

Post a Comment