Link to home
Start Free TrialLog in
Avatar of Codeaddict7423
Codeaddict7423Flag for United States of America

asked on

bind databox to table field programmatically

Hello,
I have a user control built  using Visual Studio 2005 on VB.NET and a SQL 2008 backend.
In this user contron, i have a sub coded to check to verify promo codes.  Upon promo code verification, i would like to add a discount to an event ticket price.

Below, please find my sub code:
------------
 Protected Sub btnVerifyPromos_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        ' Protected Sub btnVerifyPromos_Click(ByVal sender As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
       
        'Handles CVPromoCode.ServerValidate
               
        ' Creates myConnection as a new sqlconnection and sets it equal to DSN_PROD
        Dim myConnection As System.Data.SqlClient.SqlConnection = New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("DSN_PROD").ConnectionString)
     
        myConnection.Open()

        ' Build a sql statement string    
        Dim query1 As String = "Select PromoCode, DiscountValue FROM tblPromoCodes WHERE PromoCode = @PromoCode"

        ' Initialize the sqlCommand with the new sql string.  
        Dim Command1 As System.Data.SqlClient.SqlCommand = New System.Data.SqlClient.SqlCommand(query1, myConnection)
       
        ' Declare txtPromoCode As TextBox and find in the form.
        Dim txtPromoCode As TextBox = DirectCast(RSVPForm1.FindControl("txtPromoCode"), TextBox)
        Dim lbl_Discount As Label = DirectCast(RSVPForm1.FindControl("lbl_Discount"), Label)
        Dim txtDiscountValue As TextBox = DirectCast(RSVPForm1.FindControl("txtDiscountValue"), TextBox)
       
        Command1.Parameters.AddWithValue("@PromoCode", txtPromoCode.Text)
        ' Command1.Parameters.AddWithValue("@DiscountValue", lbl_Discount.Text)
        Command1.Parameters.AddWithValue("@DiscountValue", txtDiscountValue.Text)
       

        Dim PromoCode As String = "'"
        Dim DiscountValue As Int16 = "0"

        'Create new parameters for the sqlCommand object and initialize them to the input values.    

        'Execute the command
        PromoCode = Command1.ExecuteScalar
       
        ' Display whether the page passed validation.
        Dim lbl_message As Label = DirectCast(RSVPForm1.FindControl("lbl_message"), Label)
       
       
        If String.IsNullOrEmpty(PromoCode) Then
         
            lbl_message.Text = "Promo Code Accepted."
            'Response.Write("--" + PromoCode.ToString() + "Accepted")
            lbl_Discount.Text = "Discount Applied."
            txtDiscountValue.Text = txtPromoCode.Text
           
           
        Else
            lbl_message.Text = "Promo Code Invalid."
            'Response.Write("-- Not Accepted")
            lbl_Discount.Text = "Discount Not Applied."
            txtDiscountValue.Text = txtPromoCode.Text
           
        End If

        ' args.IsValid = False
       
        If Not String.IsNullOrEmpty(PromoCode) Then
         
            lbl_message.Text = "Promo Code Accepted."
            ' Response.Write("--" + PromoCode.ToString() + "Accepted")
            lbl_Discount.Text = "Discount Applied."
            txtDiscountValue.Text = txtPromoCode.Text
 
           
        Else
            lbl_message.Text = "Promo Code Invalid."
            'Response.Write("-- Not Accepted")
            lbl_Discount.Text = "Discount Not Applied."
            txtDiscountValue.Text = txtPromoCode.Text

        End If

         
        '******* Calculate the event price if PromoCode isValid *********          
        myConnection.Close()
                'Dim txtNumberofTickets As TextBox = RSVPForm1.FindControl("txtNumberofTickets")
        'txtNumberofTickets.Focus()
               
    End Sub
----------

The call to this sub comes from t his button:
-------
<tr>
  <td style="text-align: right; white-space: nowrap; height: 25px; background-color:#ededed">
<asp:Label ID="Label2" runat="server" Text="Promo Code:"></asp:Label>&nbsp;</td>
     
<td style="text-align: left; white-space: nowrap; height: 25px;">
    <asp:TextBox ID="txtPromoCode" Width="150px" runat="server"></asp:TextBox>  
 </td>    
 <td style="text-align: left; white-space: nowrap; height: 25px;">&nbsp; </td>
 <td style="text-align: left; white-space: nowrap; height: 25px;">
<asp:Button ID="btnVerifyPromos" runat="server" OnClick="btnVerifyPromos_Click" Text="Verify"  />
     <asp:Label ID="lbl_message" runat="server" Text="" ></asp:Label>
 </td>      
  </tr>
-----------
What I'm trying to do is to have the textbox called "txtDiscountValue" display the discounted amount and the discounted total price of the ticket.

ANY help would be greatly appreciated.
Avatar of guru_sami
guru_sami
Flag of United States of America image

Following changes are required:

1: No need for this statement
  'Command1.Parameters.AddWithValue("@DiscountValue", txtDiscountValue.Text)

2: Change ExecutedScalar to ExecuteReader  

        'Execute the command
       Dim reader As SqlDataReader = Command1.ExecuteReader
       
       If reader IsNot Nothind AndAlso eader.HasRows
          reader.Read()
          PromoCode = reader.GetString(0)
          DiscountValue = reader.GetInt16(1)
      End If

        ' Display whether the page passed validation.
        Dim lbl_message As Label = DirectCast(RSVPForm1.FindControl("lbl_message"), Label)
       
       
        If String.IsNullOrEmpty(PromoCode) Then
         
            lbl_message.Text = "Promo Code Accepted."
            'Response.Write("--" + PromoCode.ToString() + "Accepted")
            lbl_Discount.Text = "Discount Applied."
            txtDiscountValue.Text = DiscountValue.ToString()

   Else
            lbl_message.Text = "Promo Code Invalid."
            'Response.Write("-- Not Accepted")
            lbl_Discount.Text = "Discount Not Applied."
            txtDiscountValue.Text = "0"

        End If
Avatar of Codeaddict7423

ASKER

guru_sami,
Thank you for helping me.
I implemented your code suggestions and when i did, i received the following error message:
--------
Specified cast is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error:


Line 112:            reader.Read()
Line 113:            PromoCode = reader.GetString(0)
Line 114:            DiscountValue = reader.GetInt16(1)
Line 115:        End If
Line 116:
 
Source File: F:\hgacweb2\uc\RSVP\RSVP_PedBike_Promo_Test01.ascx    Line: 114
---------
http://www.h-gac.com/TRAINING/discount_coupon_test.aspx 
--------
My sub code follows:
---------
Protected Sub btnVerifyPromos_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        ' Protected Sub btnVerifyPromos_Click(ByVal sender As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
       
        'Handles CVPromoCode.ServerValidate
               
        ' Creates myConnection as a new sqlconnection and sets it equal to DSN_PROD
        Dim myConnection As System.Data.SqlClient.SqlConnection = New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("DSN_PROD").ConnectionString)
     
        myConnection.Open()

        ' Build a sql statement string    
        Dim query1 As String = "Select PromoCode, DiscountValue FROM tblPromoCodes WHERE PromoCode = @PromoCode"

        ' Initialize the sqlCommand with the new sql string.  
        Dim Command1 As System.Data.SqlClient.SqlCommand = New System.Data.SqlClient.SqlCommand(query1, myConnection)
       
        ' Declare txtPromoCode As TextBox and find in the form.
        Dim txtPromoCode As TextBox = DirectCast(RSVPForm1.FindControl("txtPromoCode"), TextBox)
        Dim lbl_Discount As Label = DirectCast(RSVPForm1.FindControl("lbl_Discount"), Label)
        Dim txtDiscountValue As TextBox = DirectCast(RSVPForm1.FindControl("txtDiscountValue"), TextBox)
       
        Command1.Parameters.AddWithValue("@PromoCode", txtPromoCode.Text)
        ' Command1.Parameters.AddWithValue("@DiscountValue", lbl_Discount.Text)
        'Command1.Parameters.AddWithValue("@DiscountValue", txtDiscountValue.Text)
       

        Dim PromoCode As String = "'"
        Dim DiscountValue As Int16 = "0"

        'Create new parameters for the sqlCommand object and initialize them to the input values.    

        'Execute the command
        Dim reader As System.Data.SqlClient.SqlDataReader = Command1.ExecuteReader
       
        If reader IsNot Nothing AndAlso reader.HasRows Then
            reader.Read()
            PromoCode = reader.GetString(0)
            DiscountValue = reader.GetInt16(1)
        End If


       
       
       
        ' Display whether the page passed validation.
        Dim lbl_message As Label = DirectCast(RSVPForm1.FindControl("lbl_message"), Label)
         
        If String.IsNullOrEmpty(PromoCode) Then
         
            lbl_message.Text = "Promo Code Accepted."
            'Response.Write("--" + PromoCode.ToString() + "Accepted")
            lbl_Discount.Text = "Discount Applied."
            txtDiscountValue.Text = DiscountValue.ToString()

        Else
            lbl_message.Text = "Promo Code Invalid."
            'Response.Write("-- Not Accepted")
            lbl_Discount.Text = "Discount Not Applied."
            txtDiscountValue.Text = "0"

        End If

        ' args.IsValid = False
       
        If Not String.IsNullOrEmpty(PromoCode) Then
         
            lbl_message.Text = "Promo Code Accepted."
            ' Response.Write("--" + PromoCode.ToString() + "Accepted")
            lbl_Discount.Text = "Discount Applied."
            txtDiscountValue.Text = DiscountValue.ToString()
 
           
        Else
            lbl_message.Text = "Promo Code Invalid."
            'Response.Write("-- Not Accepted")
            lbl_Discount.Text = "Discount Not Applied."
            txtDiscountValue.Text = "0"

        End If

         
        '******* Calculate the event price if PromoCode isValid *********
       
       
     
        myConnection.Close()
       
        'Dim txtNumberofTickets As TextBox = RSVPForm1.FindControl("txtNumberofTickets")
        'txtNumberofTickets.Focus()
               
    End Sub
------------

Please review.
what is the type of DiscountValue in your table tblPromoCodes ?
guru_sami
the table data types are like this:
---------
ID = int
PromoCode = nvarchar(100)
DiscountVaue = int
DiscountType  = nvarchar(50)
PriceRetail = int
PriceDiscounted = int
PriceTotal = int
StartTime = datetime
EndTime = datetime
CreationDate = datetime
CreatedBy = nvarchar(50)
Active = tinyint
---------
Change these two lines:

''Dim DiscountValue As Int16 = "0"
Dim DiscountValue As Integer =0


  DiscountValue = reader.GetInt32(1)
guru_sami,
IT WORKED!!!. now i see that the "amount discounted" displays the amount of the discount relative to the PromoCode.

The last piece of the puzzle is to deduct the promo discount amount from the total price.
Right now, the total price is calculated by a JavaScript as follows:
---------
<script language="JavaScript" type="text/javascript">

function RegTotal()
{
form = document.forms[0];
counter = 0;
form = document.forms[0];
            counter = 0;
            if ((form.txtNumberofTickets.value != "") || (form.txtNumberofTickets.value.length != 0)) {      
                  counter = form.txtNumberofTickets.value
            }
            
            form.Regcount.value = counter;
      
        form.Total.value = parseFloat(counter*25);
       
       


var obj = document.getElementById(hdnTotalId);

obj.value = form.Total.value;

//var obj1 = document.getElementById(Attendee_FNameId);

//obj.value below this line is what drives the second caculated total

//obj1.value = form.Attendee_FName.value;


            var obj = document.getElementById("ctl00_ctl00_cphPage_cphContent_SpecialControl_RSVPForm1_hdnTotal");
        //var obj1 = document.getElementById("ctl00_ctl00_cphPage_cphContent_SpecialControl_RSVPForm1_Attendee_FName");

            
            //obj.value = form.Total.value;
            //obj1.value = form.Attendee_FName.value;
            
            

//var p = calcTotal(obj);
//alert("Total Price = " + p);            
            

function calcTotal(obj) {
var discount = 0;

var price = obj.value;
var savings = obj.value * discount;
var total = price - savings;
return form.Total.value;

}
}

</script>
---------
 the user control code is attached for your review. This answers my original qestion. If opening  up another qestion is more appropriate, please let me know.

<%@ Control Language="VB" ClassName="RSVP_PedBike_Promo_Test01" Debug="true" AutoEventWireup="true" %>


<script runat="server">
   
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        'If (Not IsPostBack) Then
        'Dim lb As Label    
        'lb = RSVPForm1.FindControl("OrderTotalAmount2")         
        ' dd.Items.Add(New ListItem("Home Rule", "Home Rule"))
        ' dd.Items.Add(New ListItem("General Law", "General Law"))
        'End If      
        
    End Sub
  
    Protected Sub RSVPForm1_CalculateTotalEvent(ByVal e As HGACServerControls.CalculateTotalEventArgs)
        If (IsPostBack) Then
            
            'Dim totalBox As HiddenField
            
            Dim totalBox As TextBox
        
       
            'find the control
            totalBox = RSVPForm1.FindControl("hdnTotal")
                
            'Throw an exception if we could not find the total
            'If (totalBox Is Nothing) Then
            'Throw New Exception("Could not get total")
            'End If

         
            Try
                e.Total = CDec(Page.Request.Form(totalBox.UniqueID))
                
            Catch
                ' If Conversion does not work set to zero
                e.Total = New Decimal(0)
                
            End Try
            
            
        End If
    End Sub

    Protected Sub RSVPForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        'Dim hdnTotal As HiddenField
        Dim hdnTotal As TextBox = RSVPForm1.FindControl("hdnTotal")
   
        ' Dim totalBox As TextBox = RSVPForm1.FindControl("hdnTotal")
        ' Dim Attendee_FName As HiddenField
        
        'Request.Form("hdnTotal")
        
        'hdnTotal = RSVPForm1.FindControl("hdnTotal")
        'Attendee_FName = RSVPForm1.FindControl("Attendee_FName")

        'hdnTotal.Text = ("25")
        'totalBox.text = ("35")
          
        If Not (hdnTotal Is Nothing) Then
            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "hdnTotalIdScript", "var hdnTotalId = '" + hdnTotal.ClientID + "';", True)
        End If
        
        ' If Not (Attendee_FName Is Nothing) Then
        'Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "Attendee_FNameIdScript", "var Attendee_FNameId = '" + Attendee_FName.ClientID + "';", True)
        ' End If
             
        
        
         
    End Sub
        

        
    Protected Sub btnVerifyPromos_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        ' Protected Sub btnVerifyPromos_Click(ByVal sender As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
        
        'Handles CVPromoCode.ServerValidate
               
        ' Creates myConnection as a new sqlconnection and sets it equal to DSN_PROD
        Dim myConnection As System.Data.SqlClient.SqlConnection = New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("DSN_PROD").ConnectionString)
     
        myConnection.Open()

        ' Build a sql statement string    
        Dim query1 As String = "Select PromoCode, DiscountValue FROM tblPromoCodes WHERE PromoCode = @PromoCode"

        ' Initialize the sqlCommand with the new sql string.   
        Dim Command1 As System.Data.SqlClient.SqlCommand = New System.Data.SqlClient.SqlCommand(query1, myConnection)
        
        ' Declare txtPromoCode As TextBox and find in the form.
        Dim txtPromoCode As TextBox = DirectCast(RSVPForm1.FindControl("txtPromoCode"), TextBox)
        Dim lbl_Discount As Label = DirectCast(RSVPForm1.FindControl("lbl_Discount"), Label)
        Dim txtDiscountValue As TextBox = DirectCast(RSVPForm1.FindControl("txtDiscountValue"), TextBox)
        
        Command1.Parameters.AddWithValue("@PromoCode", txtPromoCode.Text)
        ' Command1.Parameters.AddWithValue("@DiscountValue", lbl_Discount.Text)
        'Command1.Parameters.AddWithValue("@DiscountValue", txtDiscountValue.Text)
        

        Dim PromoCode As String = "'"
        'Dim DiscountValue As Int16 = "0"
        Dim DiscountValue As Integer = 0


        'Create new parameters for the sqlCommand object and initialize them to the input values.     

        'Execute the command
        Dim reader As System.Data.SqlClient.SqlDataReader = Command1.ExecuteReader
       
        If reader IsNot Nothing AndAlso reader.HasRows Then
            reader.Read()
            PromoCode = reader.GetString(0)
            DiscountValue = reader.GetInt32(1)
        End If


        
        
        
        ' Display whether the page passed validation. 
        Dim lbl_message As Label = DirectCast(RSVPForm1.FindControl("lbl_message"), Label)
          
        If String.IsNullOrEmpty(PromoCode) Then
         
            lbl_message.Text = "Promo Code Accepted."
            'Response.Write("--" + PromoCode.ToString() + "Accepted")
            lbl_Discount.Text = "Discount Applied."
            txtDiscountValue.Text = DiscountValue.ToString()

        Else
            lbl_message.Text = "Promo Code Invalid."
            'Response.Write("-- Not Accepted")
            lbl_Discount.Text = "Discount Not Applied."
            txtDiscountValue.Text = "0"

        End If

        ' args.IsValid = False
        
        If Not String.IsNullOrEmpty(PromoCode) Then
         
            lbl_message.Text = "Promo Code Accepted."
            ' Response.Write("--" + PromoCode.ToString() + "Accepted")
            lbl_Discount.Text = "Discount Applied."
            txtDiscountValue.Text = DiscountValue.ToString()
 
            
        Else
            lbl_message.Text = "Promo Code Invalid."
            'Response.Write("-- Not Accepted")
            lbl_Discount.Text = "Discount Not Applied."
            txtDiscountValue.Text = "0"

        End If

         
        '******* Calculate the event price if PromoCode isValid *********
        
       
      
        myConnection.Close()
        
        'Dim txtNumberofTickets As TextBox = RSVPForm1.FindControl("txtNumberofTickets")
        'txtNumberofTickets.Focus()
               

    End Sub


  

</script>





<script language="JavaScript" type="text/javascript">

function RegTotal()
{
form = document.forms[0];
counter = 0;
form = document.forms[0];
		counter = 0;
		if ((form.txtNumberofTickets.value != "") || (form.txtNumberofTickets.value.length != 0)) {      
			counter = form.txtNumberofTickets.value
		}
		
		form.Regcount.value = counter;
	
        form.Total.value = parseFloat(counter*25);
        
       


var obj = document.getElementById(hdnTotalId);

obj.value = form.Total.value;

//var obj1 = document.getElementById(Attendee_FNameId);

//obj.value below this line is what drives the second caculated total 

//obj1.value = form.Attendee_FName.value;


		var obj = document.getElementById("ctl00_ctl00_cphPage_cphContent_SpecialControl_RSVPForm1_hdnTotal");
        //var obj1 = document.getElementById("ctl00_ctl00_cphPage_cphContent_SpecialControl_RSVPForm1_Attendee_FName");

		
		//obj.value = form.Total.value;
		//obj1.value = form.Attendee_FName.value;
		
		

//var p = calcTotal(obj);
//alert("Total Price = " + p);		
		

function calcTotal(obj) {
var discount = 0;

var price = obj.value;
var savings = obj.value * discount;
var total = price - savings;
return form.Total.value;

}
}

</script>








<div style="text-align:center"></div>
                <h3 style="text-align:center"> <br /> 
               
                  <span style="color:#66686d; font-size:20px; font-weight:bold">REGISTRATION PROMO CODE TEST</span><br /> <br /><br />
</h3>
               

<HGACServerControls:RSVPForm ID="RSVPForm1" runat="server"  creditcardonly="false"  RSVPContactEmail="luis.hernandez@h-gac.com" RSVPFinancialCode="4000-108"  RSVPCode="Registration Promo Code Test" ShowBilling="True" OnCalculateTotalEvent="RSVPForm1_CalculateTotalEvent" ShowBillingTotalLabel="false" OnLoad="RSVPForm1_Load" Width="530px" >

<AdditionalFormControls>
   <p style="font-size: x-small; color: red; text-align: center"><br /><br />
    * denotes required fields.  <br /></p>
    

  
          <table width="510" cellpadding="0" cellspacing="0" style="border-color:white" border="0">
    
            <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px; width:25%">
                    <asp:Label ID="lblFName" runat="server" AssociatedControlID="tbAttendee_FName" Text="First Name:"></asp:Label></td>
                    
                   <td style="text-align: left; white-space: nowrap; height: 25px; width:25%">
           
<asp:TextBox ID="tbAttendee_FName" runat="server"  Width="150px" MaxLength="150"  ></asp:TextBox >
                     
<asp:HiddenField ID="Attendee_FName"  runat="server" Visible="true"/>


                   
                 </td>
                    <td style="text-align: left; white-space: nowrap; height: 25px; width:5%">
                    &nbsp;<span style="color:red">*</span>
                    </td>
                   <td style="text-align: left; white-space: nowrap; height: 25px;  background-color:white">
                  <asp:RequiredFieldValidator ID="rfv_FName" runat="server" ControlToValidate="tbAttendee_FName" Display="Dynamic" ErrorMessage="First Name is required" EnableClientScript="true" SetFocusOnError="true"></asp:RequiredFieldValidator>
                   
                   
                 </td>
                        
            </tr>
            <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px; background-color:white">
                    <asp:Label ID="lblLName" runat="server" AssociatedControlID="tbLName" Text="Last Name:"></asp:Label></td>
                    
                   <td style="text-align: left; white-space: nowrap; height: 25px;  background-color:white">
                    <asp:TextBox ID="tbLName" runat="server"  Width="150px" MaxLength="200"></asp:TextBox>
                    </td>
                    <td style="text-align: left; white-space: nowrap; height: 25px;  background-color:white">
                    &nbsp;<span style="color:red">*</span>
                    </td>
                    <td style="text-align: left; white-space: nowrap; height: 25px;  background-color:white">
                 <asp:RequiredFieldValidator ID="rfv_LName" runat="server" ControlToValidate="tbLName" Display="Dynamic" ErrorMessage="Last Name is required" EnableClientScript="true" SetFocusOnError="true"></asp:RequiredFieldValidator></td>
                        
            </tr>
            
            <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px;">
                    <asp:Label ID="lblTitle" runat="server" AssociatedControlID="tbTitle" Text="Title:"></asp:Label></td>
                   <td style="text-align: left; white-space: nowrap; height: 25px;">
                    <asp:TextBox ID="tbTitle"  runat="server" Width="150px" MaxLength="200"></asp:TextBox>
                    </td>
                    <td style="text-align: right; white-space: nowrap; height: 25px;"> &nbsp;</td>
          <td style="text-align: right; white-space: nowrap; height: 25px;"> &nbsp;</td>
                    
            </tr>
            <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px;">
                    <asp:Label ID="lblOrganization" runat="server" AssociatedControlID="tbOrganization" Text="Organization:"></asp:Label></td>
                   <td style="text-align: left; white-space: nowrap; height: 25px;">
                    <asp:TextBox ID="tbOrganization" runat="server" Width="150px" MaxLength="200"></asp:TextBox>
                   </td>
                   <td style="text-align: left; white-space: nowrap; height: 25px;">&nbsp;<span style="color:red">*</span></td>
          
                    <td style="text-align: left; white-space: nowrap; height: 25px;">
                         <asp:RequiredFieldValidator ID="rfv_Organization" runat="server" ControlToValidate="tbOrganization" ErrorMessage="Organization is required" Display="Dynamic" EnableClientScript="true" SetFocusOnError="true"></asp:RequiredFieldValidator></td>
            </tr>
            
           
             <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px;">
                    <asp:Label ID="lblAddress" runat="server" AssociatedControlID="tbAddress" Text="Street:"></asp:Label></td>
                <td style="text-align: left; white-space: nowrap; height: 25px;">
                    
                <asp:TextBox ID="tbAddress" runat="server"  Width="150px" MaxLength="200"></asp:TextBox>
                        </td>
                 <td style="text-align: left; white-space: nowrap; height: 25px;">
                 &nbsp;<span style="color:red">*</span></td>
                            
                 <td style="text-align: left; white-space: nowrap; height: 25px;">
                 
                 <asp:RequiredFieldValidator ID="rfv_Address" runat="server" ControlToValidate="tbAddress" Display="Dynamic" ErrorMessage="Street is required" EnableClientScript="true" SetFocusOnError="true"></asp:RequiredFieldValidator> </td>
            </tr>
            
            <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px;">
                    <asp:Label ID="lblCity" runat="server" AssociatedControlID="tbCity" Text="City:"></asp:Label></td>
                <td style="text-align: left; white-space: nowrap; height: 25px;">
                <asp:TextBox ID="tbCity" runat="server"  Width="150px" MaxLength="200"></asp:TextBox>
                  </td>
                <td style="text-align: left; white-space: nowrap; height: 25px;">
                 &nbsp;<span style="color:red">*</span></td>
                            
                   <td><asp:RequiredFieldValidator ID="rfv_City" runat="server" ControlToValidate="tbCity"  Display="Dynamic" ErrorMessage="City is required" EnableClientScript="true" SetFocusOnError="true"></asp:RequiredFieldValidator> </td>
                            
            </tr>
             <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px; ">
                    <asp:Label ID="lblState" runat="server" AssociatedControlID="tbState" Text="State:"></asp:Label></td>
                <td style="text-align: left; white-space: nowrap; height: 25px;">
                <asp:TextBox ID="tbState" runat="server" Width="150px" MaxLength="200"></asp:TextBox>
                        </td>
                <td style="text-align: left; white-space: nowrap; height: 25px;">
                &nbsp;<span style="color:red">*</span></td>
                  <td><asp:RequiredFieldValidator ID="rfv_State" runat="server" ControlToValidate="tbState"  Display="Dynamic" ErrorMessage="State is required" EnableClientScript="true" SetFocusOnError="true"></asp:RequiredFieldValidator> </td>
                            
            </tr>
             <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px;">
                    <asp:Label ID="lblZipCode" runat="server" AssociatedControlID="tbZipCode" Text="Zip Code:"></asp:Label></td>
                <td style="text-align: left; white-space: nowrap; height: 25px;">
                <asp:TextBox ID="tbZipCode" runat="server"  Width="150px" MaxLength="100"></asp:TextBox></td>
                <td style="text-align: left; white-space: nowrap; height: 25px;">
                &nbsp;<span style="color:red">*</span></td>
                <td><asp:RequiredFieldValidator ID="rfv_ZipCode" runat="server" ControlToValidate="tbZipCode" Display="Dynamic" ErrorMessage="Zip Code is required" EnableClientScript="true" SetFocusOnError="true"></asp:RequiredFieldValidator> </td>
            </tr>
            
             <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px;">
                    <asp:Label ID="lblPhone" runat="server" AssociatedControlID="tbPhone" Text="Phone:"></asp:Label></td>
                <td style="text-align: left; white-space: nowrap; height: 25px;">
                <asp:TextBox ID="tbPhone" runat="server"  Width="150px" MaxLength="200"></asp:TextBox>
                    </td>
              <td style="text-align: left; white-space: nowrap; height: 25px;">
                &nbsp;<span style="color:red">*</span></td>
                        
                <td><asp:RequiredFieldValidator ID="rfv_Phone" runat="server" ControlToValidate="tbPhone" ErrorMessage="Phone is required" Display="Dynamic" EnableClientScript="true" SetFocusOnError="true"></asp:RequiredFieldValidator> </td>
                        
            </tr>
            
             <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px;">
                    <asp:Label ID="lblCellPhone" runat="server" AssociatedControlID="tbCellPhone" Text="Cell:"></asp:Label></td>
                   <td style="text-align: left; white-space: nowrap; height: 25px;">
                    <asp:TextBox ID="tbCellPhone"  runat="server" Width="150px" MaxLength="200"></asp:TextBox>
                    </td>
                    <td style="text-align: right; white-space: nowrap; height: 25px;"> &nbsp;</td>
          <td style="text-align: right; white-space: nowrap; height: 25px;"> &nbsp;</td>
                    
            </tr>
            
            
             
              <tr>
                <td style="text-align: right; white-space: nowrap; height: 25px;">
                <asp:Label ID="lblEmail" runat="server" AssociatedControlID="tbEmail" Text="Email:"></asp:Label></td>
               <td style="text-align: left; white-space: nowrap; height: 25px;">
               <asp:TextBox ID="tbEmail" runat="server"  Width="150px" MaxLength="200" AutoPostBack="false" ></asp:TextBox></td>
               <td style="text-align: left; white-space: nowrap; height: 25px;">&nbsp;<span style="color:red">*</span></td>
               <td style="text-align: left; white-space: nowrap; height: 25px;">
                    <asp:RequiredFieldValidator ID="rfv_Email" runat="server" ControlToValidate="tbEmail" ErrorMessage="Email is required" Display="Dynamic" EnableClientScript="true" SetFocusOnError="true"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="rfv_EmailValid" runat="server" 
                    ControlToValidate="tbEmail" ValidationExpression="^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$" Display="Dynamic" ErrorMessage="Enter Valid e-mail"></asp:RegularExpressionValidator> </td>

            </tr>
  
   
   
    <!--Promo Coupon call starts here /\/\/\/\/\/\/\/--> 
 
 <tr>
  <td style="text-align: right; white-space: nowrap; height: 25px; background-color:#ededed">
<asp:Label ID="Label2" runat="server" Text="Promo Code:"></asp:Label>&nbsp;</td> 
      
<td style="text-align: left; white-space: nowrap; height: 25px;">
    <asp:TextBox ID="txtPromoCode" Width="150px" runat="server"></asp:TextBox>   
 </td>    
   
 <td style="text-align: left; white-space: nowrap; height: 25px;">&nbsp; </td> 
  
 <td style="text-align: left; white-space: nowrap; height: 25px;">
 

<asp:Button ID="btnVerifyPromos" runat="server" OnClick="btnVerifyPromos_Click" Text="Verify"  /> 

     <asp:Label ID="lbl_message" runat="server" Text="" ></asp:Label>
 </td>      
  
  </tr>

   
   
   
  <tr>
  <td style="text-align: right; white-space: nowrap; height: 25px;">
<asp:Label ID="Label1" runat="server" Text="Number of Tickets:"></asp:Label>&nbsp;</td> 
      
<td style="text-align: left; white-space: nowrap; height: 25px;">  
<input id="txtNumberofTickets" type="text" name="txtNumberofTickets" style="background-color:#FFFFCC; width:150px" onblur="RegTotal();" value="1" />
  
   
<asp:HiddenField ID="NumberofTickets"  runat="server" Visible="true"/>

 
 </td>    
   
 <td style="text-align: left; white-space: nowrap; height: 25px;">&nbsp;</td> 
  
 <td style="text-align: left; white-space: nowrap; height: 25px;"><input type="text" name="Regcount" size="2" style="background-color:#FFFFCC" readonly="readonly" />regcount fires </td>      
  
  </tr>



 <!--Discount Value starts here /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\--> 
 
 
  <tr>
  <td style="text-align: right; white-space: nowrap; height: 25px;"><asp:Label ID="lbl_discamt" runat="server" Text="Amount of Discount:"></asp:Label>&nbsp;</td> 
      
<td style="text-align: left; white-space: nowrap; height: 25px; background-color:AliceBlue">
<asp:Label ID="lbl_Discount" runat="server" Text="" BackColor="aquamarine"></asp:Label>

<br />
     
<asp:TextBox ID="txtDiscountValue" Width="150px" runat="server" ReadOnly="true" BackColor="#F0F0F0" Text="" ></asp:TextBox>


</td>    
   
 <td style="text-align: left; white-space: nowrap; height: 25px;">&nbsp;</td> 
  
 <td style="text-align: left; white-space: nowrap; height: 25px;">&nbsp; </td>      
  
  </tr>
  
  <!--Discount Value ends here /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\--> 
 
  
  
  
  
  
    <tr>
              <td style="text-align: right; white-space: nowrap; height: 25px; vertical-align:top">
              <asp:Label ID="lblTotal" runat="server" ForeColor="crimson" Font-Bold="true" Text="Total : $"></asp:Label></td>
              <td style="text-align: left; white-space: nowrap; height: 25px;">
        
   <!--location of Total field --> 
                
                <input type="text" name="Total" size="23" value="" style="background-color:#FFFFCC;font-weight:bold;color:#FF0000;" readonly="readonly" disabled="disabled"/>  
 
  <!--location of hdnTotal field --> 
  
               <asp:TextBox ID="hdnTotal"  Width="150px" runat="server" ReadOnly="true"  Visible="false" BorderColor="red" ></asp:TextBox>
              
</td>
              <td style="text-align: left; white-space: nowrap; height: 25px; background-color:white">&nbsp;</td>         <td style="text-align: left; white-space: nowrap; height: 25px; background-color:white">&nbsp;</td>      
                    
            </tr>
  
  
  
  
   <tr style="background-color:white">
  <td style="text-align: right; white-space: nowrap; height: 25px; background-color:Beige">&nbsp;</td> 
      
<td colspan="3" style="text-align: left; white-space: nowrap; height: 25px;  background-color:Coral" >
&nbsp;


</td>    
        
  
  </tr>
  
  
  
             </table>
             
              <p></p>
             <hr />
             
&#160;&#160;&#160;&#160;&#160;&#160; 

             
             
 

            
</AdditionalFormControls>
        <RSVPResponseText>
            <font face="Arial, Helvetica, sans-serif">
            Thanks for registering! Payment of $25.00 has been received. <br /> 
If you have questions please contact Gina Mitteco:<br /> 
(713) 993-4583<br /> 
 <a href="mailto:gina.mitteco@h-gac.com">gina.mitteco@h-gac.com</a>. 
            
<br /><br />
Please print this confirmation for your records.

     </font>
        </RSVPResponseText>
</HGACServerControls:RSVPForm>
    &nbsp;

Open in new window

This might affect your javascript code....but if you want to do in code-behind you will have to change your Total textbox to asp.net textbox

 <input type="text" name="Total" size="23" value="" style="background-color:#FFFFCC;font-weight:bold;color:#FF0000;" readonly="readonly" disabled="disabled"/>  

Then may be give it ID="txtTotal"

Then Find your txtNumberofTickets and txtTotal in code-behind like:

     Dim txtTotal As TextBox = DirectCast(RSVPForm1.FindControl("txtTotal"), TextBox)
     Dim txtNumberofTickets As TextBox = DirectCast(RSVPForm1.FindControl("txtNumberofTickets"), TextBox)

Then calculate your total = price - discount

If Not String.IsEmptyOrNull(txtNumberofTickets.Text) Then

Dim nt as Integer = Convert.ToInt32((txtNumberofTickets.Text)
Dim price as Integer = nt*25
Dim total As Decimal =  price - (price * DiscountValue /100)
txtTotal .Text = total.ToString()

Else
txtTotal .Text = "0"
End If
and the above code goes in code where you have  '******* Calculate the event price if PromoCode isValid *********
guru_sami,
Thank you for the quick reply.
Indeed, I want to handle the cost calculation in the sub and do away with the JavaScript code. If possible, I would like to have be able to set the ticket price at RSVPForm1_Load and perform the calculations in the sub, transfer the calcuated ticket price (whether there is a discount or not) to the variable hdnTotal so the form can process the charge.

I will start implementing your code suggestions.
guru_sami,
I implemented the code changes you suggested and VS is indicating the following:
-----
  '******* Calculate the event price if PromoCode isValid *********
        Dim txtTotal As TextBox = DirectCast(RSVPForm1.FindControl("txtTotal"), TextBox)
        Dim txtNumberofTickets As TextBox = DirectCast(RSVPForm1.FindControl("txtNumberofTickets"), TextBox)


        If Not String.IsEmptyOrNull(txtNumberofTickets.Text) Then

            Dim nt As Integer = Convert.ToInt32((txtNumberofTickets.Text))
            Dim price As Integer = nt * 25
            Dim total As Decimal = price - (price * DiscountValue / 100)
            txtTotal.Text = total.ToString()

        Else
            txtTotal.Text = "0"
        End If
        -------

At line "If Not String.IsEmptyOrNull(txtNumberofTickets.Text) Then"
VS indicates "IsEmptyOrNull" is not a member of "sting"
??
sorry it should be --> String.IsNullOrEmpty
guru_sami,
I implemented the change suggested and uploaded.
When I clicked on "verify", i got this error:
--------
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:
Line 152:
Line 153:
Line 154:        If Not String.IsNullOrEmpty(txtNumberofTickets.Text) Then
Line 155:
Line 156:            Dim nt As Integer = Convert.ToInt32((txtNumberofTickets.Text))
Source File: F:\hgacweb2\uc\RSVP\RSVP_PedBike_Promo_Test01.ascx    Line: 154
-----------

Ok you have to change your txtNumberofTickets box to asp.net textbox and give it ID="txtNumberofTickets"

<input id="txtNumberofTickets" type="text" name="txtNumberofTickets" style="background-color:#FFFFCC; width:150px" onblur="RegTotal();" value="1" />
guru_sami,
I made the changes suggested. VS is indicating errors at the following places in the new asp:textbox
-----
    <asp:TextBox ID="txtNumberofTickets" runat="server" type="text" name="txtNumberofTickets" style="background-color:#FFFFCC; width:150px" onblur="RegTotal();" value="1"   ></asp:TextBox>
------
name="txtNumberofTickets"
value="1"
onblur="RegTotal();"

can you please review?
 <asp:TextBox ID="txtNumberofTickets" runat="server" Text="1" Width="150px" ></asp:TextBox>

make sure you set your Total text box something similar as well.
guru_sami,
Please revie my code edits for the following:
--------txtNumberofTickets
  &lt;asp:TextBox ID="txtNumberofTickets" runat="server" Text="1" Width="150px" &gt;&lt;/asp:TextBox&gt;
&lt;asp:HiddenField ID="NumberofTickets"  runat="server" Visible="true"/&gt;
------
------txtTotal
&lt;asp:TextBox ID="txtTotal" runat="server" Width="23" value="" style="background-color:#FFFFCC;font-weight:bold;color:#FF0000;" readonly="true" Enabled="false"&gt;&lt;/asp:TextBox&gt;
   &lt;!--location of hdnTotal field --&gt;
 &lt;asp:TextBox ID="hdnTotal"  Width="150px" runat="server" ReadOnly="true"  Visible="false" BorderColor="red" &gt;&lt;/asp:TextBox&gt;
-----------

             
Set the total textbox like this for now.

<asp:TextBox ID="txtTotal" runat="server" Width="23px" Enabled="false"></asp:TextBox>

Open in new window

guru_sami,
It seems to work on the total. I'm changing the size of the tota box to see better.  but it works!!!
guru_sami,
it's calculating the % discount.  This is great, if I wanted to have a hard-dollar discount, how can I change?

Also, I just tested with fake registration, and the txtTotal did display and send the amt of 22.5 (a discount of 10% off) from $25.00
in order to have the amt processed by the cc script, hdnTotal has to equal txtTotal.
Can you please help?
-->if I wanted to have a hard-dollar discount, how can I change?
This is the formula :  price - (price * DiscountValue / 100)
Change it as per your need,,,,it shouldn't be hard, it's basic maths.

-->in order to have the amt processed by the cc script, hdnTotal has to equal txtTotal.
Find the hdnTotal as you find txtTotal and set's it's Text value similar to txtTotal.


guru_sami,

I edited the following to make txtTotal = hdnTotal
------
If Not String.IsNullOrEmpty(txtNumberofTickets.Text) Then

            Dim nt As Integer = Convert.ToInt32((txtNumberofTickets.Text))
            Dim price As Integer = nt * 25
            Dim total As Decimal = price - (price * DiscountValue / 100)
            txtTotal.Text = total.ToString()
           
            Dim hdnTotal As TextBox = RSVPForm1.FindControl("hdnTotal")
            txtTotal.Text = hdnTotal.Text
        Else
            txtTotal.Text = "0"
        End If
------
can you please review?
guru_sami,
When tried this code, i did not get a calculated total...
The lines i added are:
-------
 Dim hdnTotal As TextBox = RSVPForm1.FindControl("hdnTotal")
           
            txtTotal.Text = hdnTotal.Text
------
can you please review?            

Dim hdnTotal As TextBox = DirectCast(RSVPForm1.FindControl("hdnTotal"), TextBox)
hdnTotal.Text = total.ToString()
guru_sami,
I made a slight edit to the previous code. Below, please find my change:
------
 '******* Calculate the event price if PromoCode isValid *********
        Dim txtTotal As TextBox = DirectCast(RSVPForm1.FindControl("txtTotal"), TextBox)
        Dim txtNumberofTickets As TextBox = DirectCast(RSVPForm1.FindControl("txtNumberofTickets"), TextBox)
        Dim hdnTotal As TextBox = DirectCast(RSVPForm1.FindControl("hdnTotal"), TextBox)


        If Not String.IsNullOrEmpty(txtNumberofTickets.Text) Then

            Dim nt As Integer = Convert.ToInt32((txtNumberofTickets.Text))
            Dim price As Integer = nt * 25
            Dim total As Decimal = price - (price * DiscountValue / 100)
            txtTotal.Text = total.ToString()
                       
            txtTotal.Text = hdnTotal.Text
           

        Else
            txtTotal.Text = "0"
        End If
--------

I am still not getting a calculated total.  
Can you please review?
ASKER CERTIFIED SOLUTION
Avatar of guru_sami
guru_sami
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
guru_sami,
YOU ARE A GENIUS .... hdnTotal populates to the database table.
I have a little cleanup to do and tweak the response email to carry the new hdnTotal , but the form works.

I can't thank you enough.
guru_sami continues to prove he is a genius and a master coder.
He is a tremendously knowlegeable resource and very helpful in solving problems.