Label Text Changes During Code but Won't Say Changed - vb.net

I have code in my program that updates a database. When the database has been updated, I change the text of a label to say "Last Update" and then the actual time when the update occurred. This part works perfectly.
My problem occurs when I close the program and re-open it. I want to code to check the date in the label and if the date in the label is less than the current date I want to update my database. But when I close my program and re-open it the label in the text doesn't stay.
Here is my code:
Public Sub Screen_Shown(sender As Object, e As EventArgs) Handles Me.Shown
Dim Time_of_Update = CDate(Label_Time_of_Update.Text.Split(" "c)(2).Trim())
Debug.WriteLine(Time_of_Update)
If Time_of_Update < Today Then
Update_Data()
Else
End If
End Sub
Private Sub Update_Data()
Update_Daily()
Ready_Update_Quarterly_and_Annualy()
Dim Time_of_Update = DateTime.Now
Label_Time_of_Update.Text = "Last Updated " & Time_of_Update & ""
End Sub
How can I fix this?

Go to Settings in Project properties and create a LastUpdatedDate setting:
Name == "LastUpdatedDate" basically a variable name
Type == Date
Scope == User (Application scope makes them Read Only)
Value == a valid date
This defines the setting name and data type. in code:
Dim Time_of_Update = DateTime.Now
Label_Time_of_Update.Text = "Last Updated " & Time_of_Update & ""
My.Settings.LastUpdatedDate = Time_of_Update
My.Settings.Save
next time you run:
Label_Time_of_Update.Text = My.Settings.LastUpdatedDate
Saving it as a DateTime type will make it easy to date comparison in code rather than converting it back from a String.

Related

How to get a form field to auto fill when a product is entered?

I am trying to get my form to populate the days needed for testing automatically when I enter a new record but it keeps erring out. I am very new to using VBA and Access 2016.
I have looked at some other examples that people have posted that work and cannot get it to work.
I am continually getting debugger.
Option Compare Database
Private Sub Fill_SKU_AfterUpdate()
PopulateFields
End Sub
Private Sub PopulateFields()
frmSerialTracerLog.Days_Used_For_Off_Test = DLookup("Days_Used_For_Off_Test", "tblTestDays", "Fill_SKU = '" & frmSerialTracerLog.Fill_SKU & "'")
End Sub
You probably are referring to the current form, thus use Me:
Private Sub PopulateFields()
Me!Days_Used_For_Off_Test.Value = DLookup("Days_Used_For_Off_Test", "tblTestDays", "Fill_SKU = " & Me!Fill_SKU.Value & "")
End Sub

Converting String to a DateTime or TimeValue

I have a problem trying to convert a String to a DateTime or TimeValue.
I made a little Windows Form to use as an example. Please take a look at this to see the Form:
As you can see there is a TextBox1.
Also a Timer1 with an interval of 1000 ms.
What I want is to be able to fill in a time in the textbox (like this format: 22:30:00) and when your desktop reaches this time, it will display a messagebox.
I tried several old posts and tutorials with similar problems but I can't seem to find the solution. Can anyone make a quick example using my screenshot perhaps?
This is the code someone else suggested.
Dim tsValue As TimeSpan = TimeSpan.Zero
If TimeSpan.TryParse(TextBox1.Text.Trim, tsValue) Then
If Date.Now.TimeOfDay = tsValue Then
MessageBox.Show(String.Format("Messagebox test {0}", tsValue.ToString))
End If
End If
But for some reason it does not work when I place it in my Timer.
Keep a variable with the target time (assuming it passes validation) and have your timer check if the target time matches the current time. Make sure your timer updates the date when the day changes (12:00 AM).
Private m_dteTime As DateTime
Private m_dteCurrentDate As Date = DateTime.Now.Date
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
'Validation
Try
Dim strHours As String = TextBox1.Text.Substring(0, 2)
Dim strMinutes As String = TextBox1.Text.Substring(3, 2)
Dim strSeconds As String = TextBox1.Text.Substring(6, 2)
If IsNumeric(strHours) AndAlso IsNumeric(strMinutes) And IsNumeric(strSeconds) Then
m_dteTime = DateTime.Now.Date.AddHours(Convert.ToDouble(strHours)).AddMinutes(strMinutes).AddSeconds(strSeconds)
Else
m_dteTime = DateTime.MinValue
End If
Catch ex As Exception
End Try
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If DateTime.Now.Date > m_dteCurrentDate Then
m_dteCurrentDate = DateTime.Now.Date
End If
If m_dteTime.Date = DateTime.Now.Date AndAlso m_dteTime.Hour = DateTime.Now.Hour AndAlso _
m_dteTime.Minute = DateTime.Now.Minute AndAlso m_dteTime.Second = DateTime.Now.Second Then
MsgBox("The time is now.")
End If
End Sub
The reason your code is not working is you're using "=" operator to compare two values which are highly unlikely to be equal. The thing is, you're entering the time value without milliseconds in your TextBox control, but the TimeOfDay function returns current time including milliseconds. Therefore, your message box never gets shown.
Now, there are multiple ways to get around this, but let's keep it simple. If you change "=" to "<=", it will work, but in that case your message box will continue to appear with each timer iteration, so you would have to disable timer right after or just before you show a message box. Depending on what are you trying to achieve, this could or could not be the solution for you.
If you need to keep the timer running, you can remove the millisecond part of the current time before comparing, which will give you one second to do the comparing. Also, in this case you should reduce timer interval to a lower value (500ms should be enough).
Also, if I may suggest, instead of TextBox, you should use DateTimePicker control with Format property set to Time and ShowUpDown property set to True. It will make your life easier as it will automate validation and also avoid uneeded conversions.

VB.Net affect changes to a table

I am using a datagridview to display table data and changing values of a particular cell. Depending on requirement I may need to change such values for more than one row.
I am trying to use datagridview1.CellValueChanged to populate a Dataset (i.e. create a collection of changes made) and subsequently saving the changes by clicking on a command button.
My problem is that though for each change, the sub is being called ONLY the last change is being saved. I was thinking of using the Dataset to store multiple records where the values are changed and then SAVE all the rows in the Dataset in the database table (using Update).
Could there be some solution to my predicament.
PS. Before trying this (ADO.net dataset) I was updating a temporary table and then using that I was updating the database.
Grateful for a solution please.
Code:::
Private Sub dGridVwCreaCode_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dGridVwCreaCode.CellValueChanged
Dim qryStr_CodeShtText_Changed As String
Dim var_CodeID_Changed As Long
var_CodeID_Changed = dGridVwCreaCode(e.ColumnIndex - 2, e.RowIndex).Value
qryStr_CodeShtText_Changed = "SELECT Code_ID, Code, Code_Descrip FROM Code_SAP " & _
"WHERE (Code_SAP.Code_ID = " & var_CodeID_Changed & ")"
var_CodeShtText_Changed = dGridVwCreaCode(e.ColumnIndex, e.RowIndex).Value.ToString
If Not CatGenieConnPublic.State = ConnectionState.Open Then
CatGenieConnPublic.Open()
End If
da_CodeShtText_Changed = New OleDb.OleDbDataAdapter(qryStr_CodeShtText_Changed, CatGenieConnPublic)
da_CodeShtText_Changed.Fill(ds_CodeShtText_Changed, "Code_SAP")
cb_CodeShtText_changed = New OleDb.OleDbCommandBuilder(da_CodeShtText_Changed)
ds_CodeShtText_Changed.Tables("Code_SAP").Rows(1).Item("Code_Descrip") = var_CodeShtText_Changed
To save the changes (following sub being called from a Button_Click):
Private Sub Save_Changed_CodeShtText()
da_CodeShtText_Changed.Update(ds_CodeShtText_Changed, "Code_SAP")
MsgBox("Changes saved to database....", vbOKOnly + vbInformation)
If CatGenieConnPublic.State = ConnectionState.Open Then
CatGenieConnPublic.Close()
End If
'SET BOOLEAN TO FALSE AS CHANGED VALUES HAVE BEEN SAVED
bool_CellVal_HasChanged = False
End Sub
PS. Somehow I am not able to place all the code lines together, pl pardon me.
What I was missing out on was incrementing the "row" count in the code line:
ds_CodeShtText_Changed.Tables("Code_SAP").Rows(rowNum_Increment - 1).Item("Code_Descrip") = var_CodeShtText_Changed
So every time the user changes data in the particular cell, rows number in incremented by "1" and is collected in the dataset.

Access VBA decode

I am new to VBA code, and working on a project to revised a built MS Access database that has some VBA code built from another person. Can some one explain what the code below would do? My end goal to to create a Data Entry form that would keep previous value from some fields when the users enter the next New Record. Thank you so much.
'Private Sub DocumentTypeCombo1_AfterUpdate()
'Me.DocumentNameCombo1 = Null
'Me.DocumentNameCombo1.Requery
'Me.OrderBy = "Errors DESC"
'Me.DocumentNameCombo1 = Me.DocumentNameCombo1.ItemData(0)
'End Sub
'Private Sub DocumentNameCombo1_AfterUpdate()
'Me.SubcategoryCombo1 = Null
'Me.SubcategoryCombo1.Requery
'Me.OrderBy = "SubCategory DESC"
'Me.SubcategoryCombo1 = Me.SubcategoryCombo1.ItemData(0)
'Me.DocumentNameCombo1.Tag = Me.DocumentNameCombo1
'End Sub
It is commented out, so it does nothing. Even if not, it wouldn't as it misses this line:
Me.OrderBy = "Errors DESC"
Me.OrderByOn = True
If you include the line, it will rearrange the sorting of Me.
To ...
keep previous value from some fields when the users enter the next New Record
you would set the DefaultValue (always a string value) in the AfterUpdate event:
Me!SomeControl.DefaultValue = Chr(34) & Me!SomeControl.Value & Chr(34)

Check DGV row for missing value with an sql bound back end

I am currently working in vb.net windows express 2013 with an sql back end. I am trying to create an if statement that will look at a specific cell and make a decision based on if the cell has nothing in it or not. I think the return for an sql statement is null but im not 100% sure. I have tried lots of codes I dug up on the internet but none of them have worked for me so far. Here is the line:
Dim Row_Index As Integer = DGVStart.CurrentCell.RowIndex
If DGVStart.Rows(Row_Index).Cells(1).Value Is Nothing Then
This code does work, as in the windows express is telling me the line is fine, however, it seems that I am always getting the return of nothing, even if something is in the cell.I think this problem has something to do with the way i am pulling the value. I have a datagridview checkbox column which i manually added in the design form and if i change it to cells(0), which is my manually inserted column, it picks it up every time. I need to know how to tell my program to differentiate between is null and is not null.
UPDATE: I am now running into new issues after changing to searching for dbnull. here is my code.
Private Sub DGVStart_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGVStart.CellContentClick
'dim start time
Dim start As String = TxtStart.Text
'fail safe so headers cant be clicked
If e.RowIndex = -1 Then
Exit Sub
End If
'dim row index and check, check is for the parts shear columns
Dim Row_Index As Integer = DGVStart.CurrentCell.RowIndex
'Dim check As String = DGVStart.Rows(Row_Index).Cells(2).Value
'if checkbox is clicked
If e.ColumnIndex = 0 Then
'---------------------------------------------Normal parts---------------------------------------------------------------
'If DGVStart.Rows(Row_Index).Cells(1).Value Then
If IsDBNull(DGVStart.Rows(Row_Index).Cells(3).Value) = True Then
Dim Shear As Date = DGVStart.Rows(Row_Index).Cells(5).Value
Dim Machine As Int16 = DGVStart.Rows(Row_Index).Cells(4).Value
Dim ShearNumber As String = DGVStart.Rows(Row_Index).Cells(1).Value
Dim Parts As String = DGVStart.Rows(Row_Index).Cells(3).Value
'Pull Values for sql statement and other operations
Try
'set up for checkbox event to trigger
If e.ColumnIndex = 0 Then
'safety messagebox
Dim result As Integer = MsgBox("Are you sure Shear Number " & ShearNumber & " is being started?", MessageBoxButtons.YesNo)
'if messagebox is no
If result = DialogResult.No Then
Exit Sub
'if messagebox is yes
ElseIf result = DialogResult.Yes Then
'sql update
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("UPDATE table1 SET " & start & " = getdate() Where col = value AND col = value", conn1)
With comm1.Parameters
.AddWithValue("#Shear", Shear)
.AddWithValue("#Machine", Machine)
End With
comm1.ExecuteNonQuery()
End Using
conn1.Close()
End Using
End If
End If
Catch ex As Exception
MsgBox(ex.ToString)
MsgBox("Error checking off start date for this machine, please contact the manufacturing enginnering department.")
End Try
Call refresh()
Call refresh2()
'--------------------------------------------------------Parts special--------------------------------------------------
Else
MsgBox("Parts")
End If
End If
End Sub
***Please note my sql statements have been modified to protect the company I am working for but I am sure the sql code works.
NEW PROBLEM: I am receiving a null error message because if i uncomment this line:
If DGVStart.Rows(Row_Index).Cells(1).Value Then
Then I am trying to see if a cell is null but that causes an error. I am trying to use my if statement to either run the normal parts, or special parts of my code.
Thanks,