custom validator in asp.net for gridview when item count is zero and total amount is negative (in footer) ?

I have a grid view, which has a footer . One of the property of this footer is total amount. I need to alert the user when the total amount in the footer  is negative amount and there are no items in the grid. i.e. when the items.count == 0 and when the total amount is negative.

how can I right a custom validator to achieve this ? Could someone please provide an example of this ?

tech_questionAsked:
Who is Participating?
 
Kyle_BCBSLAConnect With a Mentor Commented:
Okay.  What you want to do is have a CustomValidator control.  Put it anywhere that you would like it to be displayed.  Have the control to validate be set to the control that is hidden(I will assume it is a textbox with the id="d_total_amount").  In the ClientValidationFunction property, put the name of the javascript function: validateNonNegative

In the body of your .aspx page at the very top put this:

<script language="javascript" type="text/javascript" >
function validateNonNegative(sender, args){
      if(args.value <= 0){
            args.IsValid = false;
      }
     
      args.IsValid = true;
}
</script>

This should fire just before the page does a postback, if the page is invalid(textbox has a negative number or zero), postback will be stopped and with the appropriate error message the user will know to enter a valid(positive) amount.  Let me know if this works out for you.  
0
 
Kyle_BCBSLACommented:
Do you want the validation to be done on the client-side(immediate) or on the server-side(after posting to server)?  
0
 
tech_questionAuthor Commented:
server side please ?
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
Kyle_BCBSLACommented:
I would recommend using Client-Side validation because it will eliminate the need to make a round-trip to the server.  Making round-trips reduces website streamlined performance.  Client-Side is extremely fast!  
<asp:CustomValidator ID="[Give your validator a name]" runat="server" ErrorMessage="[error message text]"
ControlToValidate="[ID of the control you need to validate]" Display="Dynamic" ClientValidationFunction="[name of javascript function]"
Font-Bold="True" Font-Size="Large"></asp:CustomValidator>
 
If you want to use ServerSide Validation you just remove the bold text from above and in the ServerValidate event you can put your code for validating the control.  (onServerValidate)
0
 
Kyle_BCBSLACommented:
One side note:

When writing a javascript function for the CustomValidator, you need to have 2 parameters.  One should be Source and the other should be Args.  Call them what you want but it needs to be there.  
EXAMPLE SYNTAX:  
function validationFunction(Source, Args){
      //LOGIC
}

EXAMPLE FUNCTION:
function validateSentToAdjuster_dt(sender, args) {
    var checked = document.getElementById("[ID of control validating against]").checked;
    var argument = args.Value;
    if (checked == true && argument == "") {
        args.IsValid = false;
        return;
    }
    else if (checked == false && argument != "") {
        args.IsValid = false;
        return;
    }
    args.IsValid = true;
}

Your Source is the control that you specified is being validated, while Args is used to tell the CustomValidator whether it should fire or not.  (Args.IsValid = true -- Validator does not fire || Args.IsValid = false -- Validator does fire)

I hope that helps...If you need anything further just let me know.  
0
 
tech_questionAuthor Commented:
thank so much for that. I have a different problem now, I need to validate a total amount which is present in the footer of a gridview. I put a hidden field and stored this total amount in to this field and put the custom validator on this  hidden field. how can I fire this custom validator on the submit of a button ?
0
 
Kyle_BCBSLACommented:
Please send me the code for the gridview control.  I don't want the code behind, I would like to see the .aspx.  I can help you then...  
0
 
tech_questionAuthor Commented:
I actually use RadGrid but it is similar to GridView. I have posted the code below. Basically if the d_total_amount is zero or negative , I need to fire the required validations on submit of a button.
 <telerik:RadGrid ID="gridInvLines" AllowPaging="False" Skin="Office2007" 
        runat="server" AutoGenerateColumns="False" DataSourceID="odsInvLines" 
        GridLines="None" OnItemDataBound="gridInvLines_ItemDataBound" ShowFooter="True">
        <ClientSettings >
         <ClientEvents OnPopUpShowing="PopUpShowing"  />
        </ClientSettings>
        <MasterTableView DataKeyNames="LINE_NUMBER" DataSourceID="odsInvLines" EditMode="PopUp" InsertItemDisplay="Top"  AllowAutomaticInserts="true" AllowAutomaticUpdates="true" CommandItemDisplay="Top" CommandItemSettings-AddNewRecordText="Add New Line">
            <Columns>
                <telerik:GridEditCommandColumn ButtonType="LinkButton" InsertText="Save" UniqueName="EditButton">
                 <ItemStyle HorizontalAlign="Center" Width="30px" />
                </telerik:GridEditCommandColumn>
                
                
            
	    <telerik:GridBoundColumn DataField="LINE_NUMBER" HeaderText="Line Number" 
                  UniqueName="LINE_NUMBER" ReadOnly="True">
                  <HeaderStyle Width="30px" />
                  <ItemStyle HorizontalAlign="Center" />
              </telerik:GridBoundColumn> 
              
             
                           
                <telerik:GridTemplateColumn HeaderText="Quantity" UniqueName="QUANTITY" EditFormColumnIndex="1">
                    <HeaderStyle Width="30px" />
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lblQuantity" Text='<%# Eval("QUANTITY") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox runat="server" ID="txtQuantity" Text='<%# Bind("QUANTITY") %>'></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfvQuantity" ControlToValidate="txtQuantity" ErrorMessage="Please enter Quantity"
                            runat="server">*</asp:RequiredFieldValidator>
                    </EditItemTemplate>
                </telerik:GridTemplateColumn>
                
                <telerik:GridTemplateColumn HeaderText="Amount" UniqueName="UNIT_SELLING_PRICE" EditFormColumnIndex="1">
                    <HeaderStyle Width="50px" />
                    <ItemStyle HorizontalAlign="Right" Width="50px" />
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lblUnitPrice"  Text='<%# Eval("UNIT_SELLING_PRICE", "{0:C}") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox runat="server" ID="txtUnitPrice" Text='<%# Bind("UNIT_SELLING_PRICE") %>'></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfvUNIT_SELLING_PRICE" ControlToValidate="txtUnitPrice" ErrorMessage="Please enter Amount"
                            runat="server">*</asp:RequiredFieldValidator>
                    </EditItemTemplate>
                </telerik:GridTemplateColumn>
                
             
                 <telerik:GridBoundColumn DataField="TOTAL_AMOUNT" HeaderText="Total Amount"  DataFormatString="{0:c}" ReadOnly="true" ForceExtractValue="None">
                   <HeaderStyle Width="50px" />
                  <ItemStyle HorizontalAlign="Right" Width="50px" />
              </telerik:GridBoundColumn>
              
               <telerik:GridBoundColumn Visible="false" UniqueName="D_TOTAL_AMOUNT"  DataField="TOTAL_AMOUNT" HeaderText="Total Amount" DataType="System.Double"  ReadOnly="true" ForceExtractValue="None">
               </telerik:GridBoundColumn>
               
          
            </Columns>
       
       <EditFormSettings EditColumn-UpdateText="Save" CaptionFormatString="Invoice Line Information" ColumnNumber="2">
                   <FormTableItemStyle Wrap="False" Width="100%"></FormTableItemStyle>
                    <FormCaptionStyle CssClass="EditFormHeader" Width="100%"></FormCaptionStyle>
                    <FormMainTableStyle GridLines="Horizontal" CellSpacing="0" CellPadding="3" BackColor="White"
                        Width="100%" />
                    <FormTableStyle CellSpacing="0" CellPadding="2" CssClass="module" Height="110px"
                        BackColor="White" />
                    <FormTableAlternatingItemStyle Wrap="False"></FormTableAlternatingItemStyle>
 
       <PopUpSettings  Modal="true" Width="600"  />
       </EditFormSettings>
        </MasterTableView>
        <ValidationSettings CommandsToValidate="PerformInsert,Update" />
       
    </telerik:RadGrid>

Open in new window

0
 
tech_questionAuthor Commented:
apparently I did that and the validation does not fire. The alert message in the validation also does not fire. I had to make the textbox visible='true' to fire off the alert message that I put to debug  but even then the validation does not fire. What am I doing wrong ?
1) do I need to make the textbox control visible = 'true'
2) why isn't the validation firing ? I can see the first alert message that I put to debug but not the actuall error message (for this to happen I had to make the txtTotalLineAmount visible="true".
function validateTotalAmount(source, args)
                {
                  alert(parseFloat(args.Value) + "I am in debug");
                  if(parseFloat(args.Value < 0))
                  {
                    args.IsValid = false;
                  } 
 
                    //args.IsValid = true;
 
                }
 
 <tr>
            <asp:TextBox ID="txtTotalLineAmount" runat="server" visiible="false" /> 
    
           <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Invalid input"  
                ControlToValidate="txtTotalLineAmount" ClientValidationFunction="validateTotalAmount">*</asp:CustomValidator> 
   

Open in new window

0
 
Kyle_BCBSLACommented:
My mistake. I left out a very important part. After args.IsValid = False;
On the next line you need: Return;
0
 
tech_questionAuthor Commented:
It stil does not fire. what am I doing wrong ?
0
 
Kyle_BCBSLACommented:
Give me all of your code for the aspx page.  
0
 
tech_questionAuthor Commented:
kyle thanks for your help, I am actually calling the javascript from a different function and now it works.
0
 
Kyle_BCBSLACommented:
You are very welcome!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.