VB.NET 2012 : Select rows from DataView querying with 'Date' - vb.net

I have a table which contains a date column called PurchaseDate
I have a list box which displays the months. When I click a month , I need to query the dataSource and collect the rows which have the purchase date in the SelectedMonth.
dv2 = New DataView(ds.Tables(0), "PurchaseDate LIKE '" & SelectedMonth & "/%'", "BillNo", DataViewRowState.CurrentRows)
This code is not working. Because here PurchaseDate is in Date format like 'MM/DD/YYYY'. I think I need to convert the date into string before using LIKE operator. I also tried using as below. Even then, it didn't go fine.
dv1 = New DataView(ds.Tables(0), "convert(varchar2(20),PurchaseDate,103) LIKE '" & SelectedMonth & "/%'", "BillNo", DataViewRowState.CurrentRows)
Here SelectedMonth will be a string like '01', '10'..

Use Linq to avoid such issues:
Dim selectedMonth = Int32.Parse(lbMonth.Text)
Dim filteredRows = From r In ds.Tables(0)
Where r.Field(Of Date)("PurchaseDate").Month = selectedMonth
' if you need a new DataTable
Dim tblFiltered = filteredRows.CopyToDataTable()

You don't say what database you are using, so these are the culture independent date literals that I use in the same scenario...
Oracle
TO_DATE('18-Dec-2012','dd-Mon-yyyy')
SQL/Server
'18-Dec-2012'
Ms/Access (not culture independent, but it's the only thing MS/Access accepts)
#12/18/2012#
So you might format your SQL to say something like this...
PurchaseDate BETWEEN '1-Dec-2012' AND '31-Dec-2012'

Related

How to Condition the two Date and time from database into label current date and time

How to compare the date from MS Access Column "Time" in Time in my label form.
heres my code
Dim sql = "Select CompanyCode From LAPostingCoCode where CompanyCode = '" + ComboBox1.text"' AND User = '" & txtuser.text & "' AND Time = '" & LblTime.text & "'"
Using Olecon As New OleDbConnection(cons)
Using command as new OleDbDCommand(sql,olecon)
Using adapter as New OleDbDataAdapter(command)
Dim Table As New DataTable()
adapter.Fill(table)
If (table.Rows.Count > 0 ) Then
btnSave.Enabled = false
Else
btnSave.Enabled = true
End If
End Using
End Using
End using
I want to compare the date and time from database Column into my Form Label Current Date and Time. So that if the date and time in the database is 02-02-18 4:42:01, and in my label is 02-02-18 05:02:31. the button save will be enabled = true because the time is almost 5pm. when 4:42:01 is equal into time label. the save button still enabled = false.
I am using vb.net and MS access. help me please. thanks
The code will let you compare two dates , please modify the code as required :
'Assuming your date is formatted as : dd/mm/yyyy
Dim date1 = DateTime.Parse("02/05/2018")
Dim date2 = DateTime.Parse("03/07/2018")
If date1.Date >date2.Date Then
End if
Now for example , for example , you want to compare dateTime column of your table with your label's date(i mean .text),do this "
Dim dt1 = DateTime.Parse(yourDataTable(0)(3)) 'Here 0 is the row count and 3 is the column count
'Follow the first code block's code now :)
Suggestion: Please don't use direct values in your Select statement as it opens doors to Sql-Injection.
Read more about SQL-Injection
Rather,pass parameters and use your SqlCommand to pass values :
Dim cmd as new SqlCommand("Select CompanyCode From LAPostingCoCode where CompanyCode = #code",connection)
cmd.Parameters.Add("#code",SqlDbType.VarChar).Value = ComboBox1.text
And please use Parameter.Add method , most people use AddWithValue which not the proper way.Because at points, it may not cause errors/may not conflict with data but in most cases it'll corrupt the data.The reason is that , it infers the database type to query parameter.
Read more here
Hope this helps :)

How to filter out birthdays based on birth months from a data table

I'd like to get the list of people, from a data table named Patient, filtered according to their birth month. The data table has a birthday column wherein the elements have the format of mm/dd/YYYY. Any ideas on how to do this?
I'm currently using the binding source method. I managed to filter it according to other fields, and I can't think of a way on how to do this one. Thank you
`Dim bs As New BindingSource
bs.DataSource = StAnnes.Patient
If cmbFilter.Text = "Name" Then
bs.Filter = "Patient LIKE '%" & txtboxFilter.Text & "%'"
ElseIf cmbFilter.Text = "Sex" Then
bs.Filter = "Sex LIKE '%" & txtboxFilter.Text & "%'"
ElseIf cmbFilter.Text = "Month of Birth" Then
bs.Filter = "'Format('Date of Birth','mmm') LIKE 'Jan'"
ElseIf cmbFilter.Text = "Address" Then
bs.Filter = "Address LIKE '%" & txtboxFilter.Text & "%'"
End If
dgvPtList.DataSource = bs`
There is no Format function available for the Filter expression.
You can turn around the problem using a conversion with probably horrible performances.
bs.Filter = "SUBSTRING(CONVERT([Date of Birth], 'System.String'), 1,2) = '01'");
Here we try to convert the datetime column to a string, then we take the first two characters of the converted string and apply the logical comparison to the value 01 representing January. Of course this should be tested against your locale settings. The conversion produces a string that I don't know how it is formatted. I assume that the first two chars are the Month, but you need to test it in your environment.
Do not forget to put a column that contains spaces inside square brackets.

Filter DataTable by DateTime (ShortDate)

I'm working on a VB.Net project in Visual Studio 2013, and I have a data table full of rows containing ShortDate format strings in a column called "Date Purchased". I want to filter the data such that all rows that pass through the filter are imported to another data table.
For example, if the minimum filter was "01/01/1750" and the maximum filter was "01/01/2050", a row containing "4/12/1989" in the appropriate column would be imported to a different table.
The filter looks something like this:
Dim dateMin As String = "01/01/1750"
dim dateMax As String = "01/01/2050"
Dim dateExpression As String = "Date Purchased >= #" & dateMin & "# and Date Purchased <= #" & DateTime.Parse(dateMax.Text) & "#"
Dim dateFilter() = oldTable.Select(dateExpression)
For Each r As DataRow In dateFilter
newTable.ImportRow(r)
Next
My problem is that I get the error message "Additional information: Syntax error: Missing operand after 'Purchased' operator." and no rows are imported. dateExpression looks something like this:
"Date Purchased >= #1/1/1700# and Date Purchased <= #12/31/3000#"
Why doesn't this work? Any help would be appreciated, thank you.
EDIT: The problem was completely resolved by using [Date Purchased] instead of "Date Purchased". Thanks!
The problem was resolved by using [Date Purchased] instead of "Date Purchased".

where clause in select statement - datetime issues

I want to put a where clause in my select statement based on the year and month of a timestamp field in my db
I have a month and a year dropdownlist which give me the following string 01/2012
The date format in my db is "2012-01-01 00:00:00" but when I select an individual date and put it in a message box it converts to "01/01/2012"
I've altered my select statement below to reflect the converted date. However Im still not given the correct details. Any ideas? Is there a particular format that I need to use when dealing with a timestamp field? Can I even use the "Right" function in a select statement?
Dim newRecordDate As String = val1 & "/" & ComboBox2.SelectedValue
Dim sql2 As String = "Select CatA, CatB, CatC, Cost, Currency, MarketingCode, Comment, RecordDate from vw_tblP_Usage_Details where puid = '" & puid & "' right(RecordDate, 7) = '" & newRecordDate & "'"
I say use parameters and the SqlParameter class to pass parameter values to sql server from .NET client instead of using concatenation and string formatting. It makes life easier.
Something Like This:
Dim myDate As Date = DateTime.Now
Dim sql As String = "Select * from SomeTable where MyDate = #some_param"
Using Command As New SqlClient.SqlCommand(sql)
Command.Parameters.AddWithValue("#some_param", myDate)
Using reader As SqlClient.SqlDataReader = Command.ExecuteReader()
'other code here
End Using
End Using

VB.NET SQL date is changed format in query

I've got a date variable that looks like this:
Dim LogDate As Date = Date.Today.AddDays(-1)
the format comes out like: #4/5/2010#
then it goes into a SQL select query as a WHERE clause. When I debug, the query has changed this to '05/04/2010'. I want it to be in the format '04/05/2010' like it is when declared. Any ideas on how I do this?
Hee is the query:
Dim sqlCmd As New SqlCommand("SELECT TOP (100) PERCENT tblBackup.BackupName,
tblBackupArchive.BackupDate, tblStatus.Status FROM tblStatus INNER JOIN tblBackupArchive ON
tblStatus.StatusID = tblBackupArchive.StatusID INNER JOIN tblBackup ON tblBackupArchive.BackupID =
tblBackup.BackupID INNER JOIN tblClient ON tblBackup.ClientID = tblClient.ClientID WHERE tblBackupArchive.BackupDate = '" & LogDate & "' AND (tblBackupArchive.StatusID = 3) ORDER BY
tblBackupArchive.BackupDate DESC", connection)
-- Jonesy
The best way would be to use a SQLCommand object with a suitable named parameter in the where clause - this would make the formatting of the textual representation of the date totally beside the point...
Another approach, if you're using MS-SQL, would be to use a date in the following format:
Where date = '20100504'
Be careful when using dates though - remember that behind the scenes they are DateTimes...
Martin.