Solved

SqlClient.SqlDataAdapter(strSQL, connection) - with a Date as a string :(

Posted on 2006-10-28
9
627 Views
Last Modified: 2008-02-01
I have made a simple form with a Crystal Reports control embedded, with the simple simple code below to bind some data to it.
=====================================

  Dim daT1, daT2 As SqlClient.SqlDataAdapter
        Dim LACARSDataSet As DataSet
        Dim strSQL As String
        Dim connection As New SqlConnection(DataDB.GetConnStr)
        connection.Open()

        LACARSDataSet = New DataSet


        strSQL = "SELECT * FROM client WHERE ClientID = '" & intClientID & "'"
        daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
        daT2.Fill(LACARSDataSet, "client")


        strSQL = "SELECT * FROM driver"
        daT1 = New SqlClient.SqlDataAdapter(strSQL, connection)
        daT1.Fill(LACARSDataSet, "driver")

        If AllThisMonth Then
            'strSQL = "SELECT * FROM job WHERE PickupDateTime > DateAdd(Month, -2, " & DateTime.Now().ToShortDateString() & ")"
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & DateTime.Now().AddMonths(-2).ToShortDateString() & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        Else
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & dtFrom.ToShortDateString() & "' AND PickupDateTime < '" & dtTo.ToShortDateString() & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        End If



        Dim rpt As New ClientsReport
        rpt.SetDataSource(LACARSDataSet)
        CrystalReportViewer1.ReportSource = rpt

        connection.Close()


=====================================

If you look in the " If AllThisMonth Then" if statement you will see that with this simple code I am trying to display only a specific date range in the Crystal Report.

However...

strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & DateTime.Now().AddMonths(-2).ToShortDateString() & "'"

Creating an SQL string like this would work well in something that queries a DB directly, BUT
with the SqlDataAdapter, I have compile errors with the date string if its not in .ToShortDateString and when it is it plain just doesnt have an effect.
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")

I can only assume that SqlClient.SqlDataAdapter(strSQL, connection) does not know who to convert a sstring of a Date into an actual date as I would be able to normally.

I've explained this poorly, but I've no real understanding of why the DataSet wont fill the data with the correct time-relevent records and why with this simple code (i am new to CR and merely want this one report to show with no hassle) the date cant be read as a string.

I hope someone understands my ramblings and can help. Thanks.
0
Comment
Question by:deecree
  • 2
  • 2
  • 2
9 Comments
 
LVL 41

Expert Comment

by:graye
ID: 17829393
The DateTime format for SQL Server wants the "medium" date format

.ToString("MMM d yyyy")

0
 

Author Comment

by:deecree
ID: 17829538
System.Data.SqlClient.SqlException was unhandled
  Class=16
  ErrorCode=-2146232060
  LineNumber=1
  Message="Conversion failed when converting datetime from character string."
  Number=241
  Procedure=""
  Server="localhost"
  Source=".Net SqlClient Data Provider"
  State=1
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlDataReader.HasMoreRows()
       at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)
       at System.Data.SqlClient.SqlDataReader.Read()
       at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping)
       at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)
       at System.Data.Common.DataAdapter.Fill(DataSet dataSet, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
       at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable)
       at LACARS.ReportsClients.DoReport() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\LACARS\LACARS\ReportsClients.vb:line 48
       at LACARS.ReportsClients.btnGo_Click(Object sender, EventArgs e) in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\LACARS\LACARS\ReportsClients.vb:line 116
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at LACARS.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
==========================

This gives me this above exception at line;
            daT2.Fill(LACARSDataSet, "job")

in this If statement...

        If AllThisMonth Then
            'strSQL = "SELECT * FROM job WHERE PickupDateTime > DateAdd(Month, -2, " & DateTime.Now().ToShortDateString() & ")"
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & DateTime.Now().AddMonths(-2).ToString("MMM d yyyy") & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        Else
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & dtFrom.ToString("MMM d yyyy") & "' AND PickupDateTime < '" & dtTo.ToString("MMM d yyyy") & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        End If

====================

This is the exception i was alluding at in the first post.
0
 
LVL 41

Expert Comment

by:graye
ID: 17829591
Humph... that should have worked.

Add a break (or a debug.print) to display the final value for strSQL to make sure it appears formatted correctly.
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 

Author Comment

by:deecree
ID: 17829894
SELECT * FROM job WHERE PickupDateTime > 'jul 29 2006' AND PickupDateTime < 'oct 29 2006'

I believe this is correct. I have been working on this on and off for about 2 weeks now and growing extremely bitter. Please help.
0
 
LVL 35

Accepted Solution

by:
YZlat earned 500 total points
ID: 17833663
did you try changing it to

SELECT * FROM job WHERE PickupDateTime BETWEEN 'jul 29 2006' AND  'oct 29 2006'

or

or

SELECT * FROM job WHERE PickupDateTime BETWEEN '07/27/2006' AND '10/29/2006'


SELECT * FROM job WHERE PickupDateTime > '07/27/2006' AND PickupDateTime < '10/29/2006'
0
 
LVL 35

Expert Comment

by:YZlat
ID: 17833679
BETWEEN is better to use than <
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Get month and date in a format 4 35
SSIS Start 2 21
PowerShell:  Column widths won't expand 3 22
C# Service FileSystemwatcher isse 9 28
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question