I am trying to find out how to compare two dates in a visual basic database - vb.net

I currently have a visual basic database made in Microsoft access. In this database, I allow the user to enter a date in a text box and this date gets saved to the database. I want to compare the dates "on the database!". The hard part is that the dates are entered in the same text box but saved on different rows. I need to compare the different dates in the rows of the database.

Fetch data from the database and use FOR EACH loop to compare. A sample code is as follows:
Dim con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=Test.accdb;Persist Security Info=False;")
con.Open()
Dim cmd As New OleDbCommand("SELECT date_col FROM my_table", con)
cmd.CommandType = CommandType.Text
Dim reader As OleDbDataReader = cmd.ExecuteReader()
Dim dt As DataTable = reader.GetSchemaTable()
For Each row As DataRow In dt.Rows
If row.Item("date_col") = **your_criteria** Then
**your_other_statements**
End if
Next row
con.Close()
Hope this will help

Related

Naming Column Header Based On Results From Database

net and would to have the Header Text of columns in a datagridview be named after results from the database, e.g the query in my code returns four dates,30/08/2017,04/09/2017,21/09/2017 and 03/02/2018. My aim is to have the column headers in the data grid named after those dates. Your help will highly be appreciated.
sql = "SELECT COUNT (ServiceDate) As NoOfServiceDates FROM (SELECT DISTINCT ServiceDate FROM tblattendance)"
Using command = New OleDbCommand(sql, connection)
Using reader = command.ExecuteReader
reader.Read()
ColumnNo = CInt(reader("NoOfServiceDates")).ToString
End Using
End Using
DataGridView1.ColumnCount = ColumnNo
For i = 0 To DataGridView1.Columns.Count - 1
sql = "SELECT DISTINCT ServiceDate FROM tblattendance"
Using command = New OleDbCommand(sql, connection)
Using reader = command.ExecuteReader
While reader.Read
DataGridView1.Columns(i).HeaderText = reader("ServiceDate").ToString
End While
End Using
End Using
Next
The current code re-runs the query each time through the column count loop, meaning it will set the column header for that column to all of the date values in sequence, so the last value in the query shows in the all the columns. You only need to run the query once:
Dim i As Integer = 0
sql = "SELECT DISTINCT ServiceDate FROM tblattendance"
Using command As New OleDbCommand(sql, connection), _
reader As OleDbDatareader = command.ExecuteReader()
While reader.Read
DataGridView1.Columns(i).HeaderText = reader("ServiceDate").ToString
i+= 1
End While
End Using
Additionally, this still results in two separate trips to the database, where you go once to get the count and again to get the values. Not only is this very bad for performance, it leaves you open to a bug where another user changes your data from one query to the next.
There are several ways you can get this down to one trip to the database: loading the results into memory via a List or DataTable, changing the SQL to include the count and the values together, or adding a new column each time through the list. Here's an example using the last option:
DataGridView1.Columns.Clear()
Dim sql As String = "SELECT DISTINCT ServiceDate FROM tblattendance"
Using connection As New OleDbConnection("string here"), _
command As New OleDbCommand(sql, connection)
connection.Open()
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read
Dim column As String = reader("ServiceDate").ToString()
DataGridView1.Columns.Add(column, column)
End While
End Using
End Using
Even better if you can use something like Sql Server's PIVOT keyword in combination with the DataGridView's AutoGenerateColumns feature for DataBinding, where you will write ONE SQL statement that has both column info and data, and simply bind the result set to the grid.
The For Next is incorrect. You execute your command for every column, when you only need to execute it once. The last result from the DataReader will be the header for every column as currently written.
You should iterate through your DataReader and increment the cursor variable there:
Dim i As Integer = 0
Using command = New OleDbCommand(sql, connection)
Using reader = command.ExecuteReader
While reader.Read
DataGridView1.Columns(i).HeaderText = reader("ServiceDate").ToString
i += 1
End While
End Using
End Using

Checking a database for specific dates to prevent a booking cross over

I have an ASPX web form where a logged-in user will be able to choose from a number of suit jacket sizes already stored in a database table. Once chosen the jacket size along with a from and to date for a booking the data is entered into a booking table with the relevant information.
I need help with code that will ensure that when another user chooses a suit jacket size they cannot use the same dates that are stored in the booking table for that size. The output would be in a label with an error message telling the user that the jacket size is unavailable for these dates.
I am using ASP.NET and the language VB for all of this work.
Any help would be appreciated!
This can be done with an If...Then statement check and a SQL query for the lookup.
Dim mySqlConnection As New SqlConnection("Your connection string")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "SELECT [ID] FROM [Table] WHERE (JacketSize = #jacketSize AND (DateFrom <= #dateWanted AND DateTo >= #dateWanted))"
cmd.CommandType = CommandType.Text
cmd.Connection = mySqlConnection
cmd.Parameters.Add("#jacketSize", 'JacketSize field')
cmd.Parameters.Add("#dateWanted", 'DateWanted field')
mySqlConnection.Open()
reader = cmd.ExecuteReader()
If (reader.HasRows = TRUE) Then
'code to execute if date is taken'
Else
'code to execute if date is not taken'
End If
mySqlConnection.Close()
Edit: Forgot to add the parameters. Thanks Andrew Morton.

How I handle duplicated record in textbox.AutoCompleteCustomSource in VB.net

I wrote a code for auto complete textbox in vb.net.
I have textbox search for the company name in 'company_list' table.
But some company have exactly same name, so when I input the name, it shows just 1 text.
I'd like to make these two names when I input the textbox.
Below is my code.
Dim sql as String = "SELECT * FROM company_info"
cmd = New MySqlCommand(sql, con)
con.Open()
adapter = New MySqlDataAdapter(cmd)
Dim dt As New DataTable
adapter.Fill(dt)
cName.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
cName.AutoCompleteCustomSource.Add(r.item(1).ToString)
Next
con.Close()
I have two same company name as below.
[TKTech]
[TKTech]
These two are totally different company with same name, so I need to choice between them.
When I input to textbox(cName), it just show 1 name for these company.
Please let me know how I handle it.
Thank you in advance.
Frank

Get last UserID from SqlServer to textbox control

I have a table customers where each cust has UserID as "A000" now I need to get the last entered ID from the database and display it in my textbox.
Can anyone suggest me how do I do this?
As I have seen many articles describing about
SELECT ##IDENTITY
SELECT SCOPE_IDENTITY()
SELECT IDENT_CURRENT('TableName')
but unable to know where to use it correctly.
And here is how I'm doing it :
Dim strConnection As String = "Data Source=.\SqlExpress;Initial Catalog=Subscription;Integrated Security=True"
'Establish SQL Connection
Dim con As New SqlConnection(strConnection)
'Open database connection to connect to SQL Server
con.Open()
'Data table is used to bind the resultant data
Dim dtusers As New DataTable()
'Create a new data adapter based on the specified query.
Dim da As New SqlDataAdapter("SELECT MAX(UserID) FROM Customers", con)
Dim cmd As New SqlCommandBuilder(da)
da.Fill(dtusers)
con.Close()
Use ExecuteScalar :
Dim comm as new SqlCommand
comm.CommandText = "SELECT MAX(UserID) FROM Customers"
comm.Connection = con
Dim MaxUserID as object = comm.ExecuteScalar()
Use the ExecuteScalar method to retrieve a single value (for example,
an aggregate value) from a database
Side Note : ExecuteScalar() may return a null reference (Nothing in VB.NET) if the result of the command is empty like when there are no records in the table or there is condition that doesn't produce any records. Make sure you check that before assigning the value to your TextBox.

VB.NET 2010 database search

I have a ms access database connected to my vb application through the data wizard.
i want to allow the user to search the database and display their results on a datagrid.
for example user searches for 50 – 55 year Old man under 1.8 meters in height
so far i can display the total amount of people on the database with this code
Private Sub lblTotalPeople_Click(sender As System.Object, e As System.EventArgs) Handles lblTotalPeople.Click
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\AssignmentDatabase.accdb")
' Use wildcard'
Dim cmd As OleDbCommand = New OleDbCommand("Select COUNT(*) From Table1", con)
'' or Where username='" & TextBox1.Text & "'
con.Open()
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
myDA.Fill(myDataSet, "Table1")
DataGridView2.DataSource = myDataSet.Tables("Table1").DefaultView
End Sub
how would i search the database based on what the user searches or what would i use?
Assuming you don't already you need to learn how to use SQL.
In your code above the SQL statement is
Select COUNT(*) From Table1
You would need to replace this SQL with a search that uses a value from the user (most likely from a textbox). This text
'' or Where username='" & TextBox1.Text & "'
appears to be part way to some SQL that may work but it looks dangerous. You should also research SQL Injection as using this directly means users could access/damage your Access database.