We help IT Professionals succeed at work.
Troubleshooting Question

Pass in DateTime Filter using Javascript / aspx.vb

58 Views
Last Modified: 2020-08-18
Hello;

I would like to pass in the values from datetime picker into the code behind aspx.vb.

Below I have called the datetime picker in asp

<script type="text/javascript">
        $(function () {
            $('[id*=txtFromDate]').datepicker({
                changeMonth: true,
                changeYear: true,
                format: "dd/mm/yyyy",
                language: "tr"
            });
        });
    </script>


    <script type="text/javascript">
        $(function () {
            $('[id*=txtToDate]').datepicker({
                changeMonth: true,
                changeYear: true,
                format: "dd/mm/yyyy",
                language: "tr"
            });
        });
    </script>
 
<div>
 <asp:TextBox ID="txtFromDate"    placeholder="Select Date From..."  runat="server"  > 
</asp:TextBox>
    <span class="add-on"><i class="icon-remove"></i></span>
    <span class="add-on"><i class="icon-calendar"></i></span>
               
    <asp:TextBox ID="txtToDate"    placeholder="Select Date To..."  runat="server" ></asp:TextBox>
    <span class="add-on"><i class="icon-remove"></i></span>
    <span class="add-on"><i class="icon-calendar"></i></span>


    <button type="button" class="btn btn-success btn-sm" runat="server" OnClick="SearchDate" >Search</button>
     <button type="button" class="btn btn-danger btn-sm" runat="server" OnClick="Clear" >Clear</button>
            </div>
Below is where I am calling the value into the Function; I use a Stored Procedure to filter the records in the grid view
 Dim dWO_DDDFrom As String = Request.Form(txtFromDate.UniqueID)
 sql += " AND ARCHIVED IN ( 'N') AND WO_DUE_DATE >=  @WO_DUE_DATE_FROM  "
 cmd.Parameters.AddWithValue("@WO_DUE_DATE_FROM", dWO_DDDFrom)
I am unsure if I need to format the date when I call the on-click button and if so how do I format the date; I have tried the following: 
Request.Form(txtFromDate.UniqueID)
Any help would be most helpful.

Thanks a milion.
Comment
Watch Question

Máté FarkasSQL Server Consultant
CERTIFIED EXPERT

Commented:
Why don't you use just:
 Dim dWO_DDDFrom As String = txtFromDate.Text
you don't need to extract value from the form because asp.net automatically build up the object model with the form values.
CERTIFIED EXPERT

Commented:
I am unsure if I need to format the date when I call the on-click button and if so how do I format the date; 

you are getting what is posted/ entered. so, it depends on how you "define" your date in your form, but since it's in "dd/mm/yyyy" format, you need to reformat it back to "mm/dd/yyyy", or "yyyy/mm/dd" in order to store correct value into database.
Maureen ConwaySoftware Developer

Author

Commented:
Thanks Ryan; can you give me an example.  I call the function on click; should I format the date in here?
Máté FarkasSQL Server Consultant
CERTIFIED EXPERT

Commented:
In fact you don't need to format the date if you use the followin formats:
  • MM/DD/YYYY or M/D/YYYY
  • YYYY/MM/DD or YYYY/M/D
  • YYYY-MM-DD or YYYY-M-D
CERTIFIED EXPERT

Commented:
can you give me an example.  I call the function on click; should I format the date in here? 

for user experience, you could do it at code behind:

something like this:

Dim dWO_DDDFrom As String = "14/08/2020" 'just an example
        Dim reformatted As String = DateTime.ParseExact(dWO_DDDFrom, "dd/MM/yyyy", Nothing).ToString("yyyy/MM/dd")

OR you would need to save another hidden value for reformatted date value in your form, which will then post to code behind, and we will refer to that instead.

but I think method one above is more straight forward.
Maureen ConwaySoftware Developer

Author

Commented:
Hi Mate

When I input the date as your example below; it works perfect

But when I input the txtFromDate from the system throws an error

Dim dWO_DDDFrom As String = txtFromDate.Text
                    Dim dWO_DDDFrom As String = "14/08/2020" 'just an example
Máté FarkasSQL Server Consultant
CERTIFIED EXPERT

Commented:
Because you use date format DD/MM/YYYY. This does not work.
You have convert it to one of the formats I recommended before.
3 possible solutions:
  1. On client side in javascript: use a DateTime picker which can produce date value in acceptable formats (see my previous comment)
  2. On server side in VB.NET: Dim dWO_DDDFrom As String = DateTime.Parse(txtFromDate.Text, "dd/MM/yyyy").ToString("yyyy/MM/dd") 
  3. On database side in SQL: 
sql += " AND ARCHIVED IN ( 'N') AND WO_DUE_DATE >= convert(datetime, @WO_DUE_DATE_FROM, 103) "
Maureen ConwaySoftware Developer

Author

Commented:
I have added the below and it throws the exception when it tries to parse the date time
 Dim dWO_DDDFrom As DateTime

                    If Not DateTime.TryParse(txtFromDate.Text, dWO_DDDFrom) Then
                        Throw New ArgumentException("Unable to parse DateTime from txtFromDate ")
                    End If
                    Dim reformattedDateOfBirth As String = dWO_DDDFrom.ToString("yyyy-MM-dd")
CERTIFIED EXPERT

Commented:
try debug what's the value of txtFromDate.Text.

and what's the variable type of dWO_DDDFrom  ?
Maureen ConwaySoftware Developer

Author

Commented:
Hi guys;

I am still having issues: I tried all different combinations; the txtToDate and txtFromDate retruns a value but when I add it to the string it messes up.
I receive the following: 

String was not recognized as a valid DateTime.



  Dim dWO_To As String = DateTime.ParseExact(txtToDate.Text, "dd/MM/yyyy", Nothing).ToString("MM/dd/yyyy")
                    Dim dWO_From As String = DateTime.ParseExact(txtFromDate.Text, "dd/MM/yyyy", Nothing).ToString("MM/dd/yyyy")
                    'Dim myScript As String = "window.alert('From Date: ' + dWO_From);"


                    If chkWODueDate.Checked = True Then


                        sql += "  AND WO_DUE_DATE >=  @WO_DUE_DATE_FROM  AND WO_DUE_DATE < @WO_DUE_DATE_TO "
                        cmd.Parameters.AddWithValue("@WO_DUE_DATE_FROM", dWO_From)
                        cmd.Parameters.AddWithValue("@WO_DUE_DATE_TO", dWO_To)
                    End If
                   
CERTIFIED EXPERT

Commented:
can you tell us what's the value of
txtToDate.Text
?

meaning to say, what have been entered into texbox: txtToDate?

Maureen ConwaySoftware Developer

Author

Commented:
Dates are taken from a datetimepicker using Javascript

  <script type="text/javascript">
        $(function () {
            $('[id*=txtFromDate]').datepicker({
                changeMonth: true,
                changeYear: true,
                format: "dd/mm/yyyy",
                language: "tr"
            });
        });
    </script>


    <script type="text/javascript">
        $(function () {
            $('[id*=txtToDate]').datepicker({
                changeMonth: true,
                changeYear: true,
                format: "dd/mm/yyyy",
                language: "tr"
            });
        });
    </script>




     <asp:TextBox ID="txtFromDate"    placeholder="Select Date From..."  runat="server"   > </asp:TextBox>
                <span class="add-on"><i class="icon-remove"></i></span>
                <span class="add-on"><i class="icon-calendar"></i></span>
                 <%--SHOW THE SELECTED DATE.--%>
                <p id="newDateFormat" runat="server"></p>


               <asp:TextBox ID="txtToDate"    placeholder="Select Date To..."  runat="server"      ></asp:TextBox>
                <span class="add-on"><i class="icon-remove"></i></span>
                <span class="add-on"><i class="icon-calendar"></i></span>


                <button type="button" class="btn btn-success btn-sm" runat="server" OnClick="Search" >Search</button>
                <button type="button" class="btn btn-danger btn-sm" runat="server" OnClick="Clear" >Clear</button>

Maureen ConwaySoftware Developer

Author

Commented:

0x800a1391 - JavaScript runtime error: 'Search' is undefined

When I search in debug; I get the above error; so the dates are not passed into the search part
Máté FarkasSQL Server Consultant
CERTIFIED EXPERT

Commented:
I already mentioned that date format DD/MM/YYYY does not work for automatic date parsing (DateTime.TryParse).
You have to use MM/DD/YYYY or YYYY/MM/DD format but you still use the wrong format:
  <script type="text/javascript">
        $(function () {
            $('[id*=txtFromDate]').datepicker({
                changeMonth: true,
                changeYear: true,
                format: "dd/mm/yyyy",
                language: "tr"
            });
        });
    </script>
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Maureen ConwaySoftware Developer

Author

Commented:
I will try the above; what do you use to call the datetimepicker
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Maureen ConwaySoftware Developer

Author

Commented:
I changed this to the below:
The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.


<script type="text/javascript">
        $(function () {
            $('[id*=txtFromDate]').datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: "dd/mm/yy",
                language: "tr"
            });
        });
    </script>


    <script type="text/javascript">
        $(function () {
            $('[id*=txtToDate]').datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: "dd/mm/yy",
                language: "tr"
            });
        });
    </script>








  <asp:TextBox ID="txtFromDate"    placeholder="Select Date From..."  runat="server"   > </asp:TextBox>
                <span class="add-on"><i class="icon-remove"></i></span>
                <span class="add-on"><i class="icon-calendar"></i></span>
             

               <asp:TextBox ID="txtToDate"    placeholder="Select Date To..."  runat="server"      ></asp:TextBox>
                <span class="add-on"><i class="icon-remove"></i></span>
                <span class="add-on"><i class="icon-calendar"></i></span>

                <asp:Button ID="btnSearch" CssClass="btn btn-success btn-sm" runat="server" Text="Search Dates" />



  Protected Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
        Dim dWO_To As String = DateTime.ParseExact(txtToDate.Text, "dd/MM/yyyy", Nothing).ToString("MM/dd/yyyy")
        Dim dWO_From As String = DateTime.ParseExact(txtFromDate.Text, "dd/MM/yyyy", Nothing).ToString("MM/dd/yyyy")

        Response.Write("dWO_To = " + dWO_To + "<br>")
        Response.Write("dWO_From = " + dWO_From + "<br>")
    End Sub




CERTIFIED EXPERT

Commented:
so... ??

can you add a break point in your codes and debug what's the value of
txtFromDate.Text
?

if the value posted are in dd/MM/yyyy format, then it should be able to parse without any error.
Maureen ConwaySoftware Developer

Author

Commented:

The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.

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.FormatException: The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.

Source Error:

Line 232: Line 233:    Protected Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Line 234:        Dim dWO_To As String = DateTime.ParseExact(txtToDate.Text, "dd/MM/yyyy", Nothing).ToString("MM/dd/yyyy")
Line 235:        Dim dWO_From As String = DateTime.ParseExact(txtFromDate.Text, "dd/MM/yyyy", Nothing).ToString("MM/dd/yyyy") Line 236:
Maureen ConwaySoftware Developer

Author

Commented:
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src='https://kit.fontawesome.com/a076d05399.js'></script>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
   
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
 


   
    <!-- Bootstrap DatePicker -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" type="text/css"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js" type="text/javascript"></script>
    <!-- Bootstrap DatePicker -->
   
Maureen ConwaySoftware Developer

Author

Commented:
Think it is a date issue as when I input the dates to 02/09 and 10/09 all works so I guess it reads MM/DD/YYY
CERTIFIED EXPERT

Commented:
Think it is a date issue as when I input the dates to 02/09 and 10/09 all works so I guess it reads MM/DD/YYY                                   
Well... don't guess, but as mentioned, observe what is being captured at web front, and then debug with break point at code behind.

It should be pretty straight forward for such debugging.
Maureen ConwaySoftware Developer

Author

Commented:
Thanks a million to both of you for your help; really appreciate it; its working perfect now!

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.