I have two TextBox elements: textbox1 for hour and textbox2 for minutes. I've tried a lot of codes but they didn't work for me. I always ended up getting:
Conversion from string "1" to type 'Date' is not valid.
I want to display time (in format hh:mm) on a label from two textboxes (textbox1 and textbox2).
I ~think~ you're trying to parse the values from the TextBoxes into a DateTime, and then display that in a Label? If so, try something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As DateTime
If DateTime.TryParse(TextBox1.Text & ":" & TextBox2.Text, dt) Then
Label1.Text = dt.ToString
End If
End Sub
If you want only the Time portion displayed, then:
Label1.Text = dt.ToString("h:mm tt")
First of,u didn't mention any code u tried so far.However the solution would be :
textbox1.text=DateTime.Now.ToString("HH")
textbox2.text=DateTime.Now.ToString("mm")
The exception u r getting Cannot convert string to date,this can be fixed by using ToString.In the code, HH stands for Hours and mm stands for minutes
For better understanding , read the documentation of DateTime.Now
Related
I want to calculate each line: it's like first line 123*1.616 and the second line 213*1.616, and display each total.
Every number entred in the kilogram textbox will mutiply 1.616 and then show the result in the kati label.
Here is my code:
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Enter
For Each digit In (TextBox1.Text)
total1 = Val(digit) * 1.616
Label9.Text = total1
Next
Label9.Text = total1
End sub
Please help me find some solution or explanation to achieve the output.
This should work
Private FACTOR As Decimal = 1.616
Private SEPARATOR As String = Environment.NewLine
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Click
Label9.Text = TextBox1.Text.
Split({SEPARATOR}, StringSplitOptions.RemoveEmptyEntries).
Select(Function(s1) $"{Decimal.Parse(s1) * FACTOR:0.00#}").
Aggregate(Function(s1, s2) $"{s1}{SEPARATOR}{s2}")
End Sub
Here are the functions in the LINQ
Split makes an array out of each line in the TextBox using SEPARATOR as the delimiter
Select transforms the elements into their value times FACTOR
Aggregate puts the elements back together into a SEPERATOR delimited string
Why didn't your original code work?
You were iterating over each char in the text, and multiplying the char by a float (Option Strict On, as suggested in the comments would have prevented that).
Then in each iteration, you do (simplified) Label9.Text = Val(digit) * 1.616 which overwrites the Label every time.
If you were to step through in debug (also suggested in comments), you would see the Label becoming 1x1.616=1.616, 2x1.616=3.232, 3x1.616=4.848, etc. The result was the very last character in your TextBox, '3', times 1.161 = 4.848. Obviously, this was not what you wanted. You needed to instead iterate over each entire number. The multiline TextBox separates each line with a new line. So we iterate over each line instead.
you can use split string by vbCrLf
Sub main()
Dim multilinetext As String =
"10
20
30
40
50
60"
Dim number_array = multilinetext.Split(vbCrLf)
Dim output As Integer = 0
For Each i In number_array
output += i
Next
Stop
End Sub
My code is as follows:
Private Sub tbRcvrDepartTime_textchanged(sender As Object, e As EventArgs) Handles tbRcvrDepartTime.TextChanged
'Converts the 90 Receiver Arrival & Departures Date & Times to a string for comparison
Dim raTime As String = tbRcvrArriveTime.Text 'Takes the Time only String and converts to string
Dim raDate As String = dpRcvrArriveDate.Text 'Takes the DateTimePicker and converts date to string
Dim raDateString = String.Concat(raDate, " ", raTime) 'Puts together the Date & Time into one continuous string
'Dim raDateFormat As String = "MM-dd-yyyy HH:mm" 'Sets the String to Date style Format
Dim raResultDate As Date = CDate(raDateString) 'Finalizes the String for use in below comparison
Dim rdTime As String = tbRcvrDepartTime.Text 'Takes the Time only String and converts to string
Dim rdDate As String = dpRcvrDepartDate.Text 'Takes the DateTimePicker and converts date to string
Dim rdDateString = String.Concat(rdDate, " ", rdTime) 'Puts together the Date & Time into one continuous string
'Dim rdDateFormat As String = "MM-dd-yyyy HH:mm" 'Sets the String to Date Format
Dim rdResultDate As Date = CDate(rdDateString) 'Finalizes the String for use in below comparison
'Checks to see if 2 or more hours have elapsed since Receiver Arrival/Departure Date & Time
Dim elapsedR As TimeSpan = rdResultDate.Subtract(raResultDate)
tbRcvrDepartTime.BackColor = If(elapsedR.TotalMinutes > 120, Color.LightPink, Color.White)
End Sub
Both raTime & rdTime are separate textboxes.
Both raDate & rdDate are datetimepickers.
When I run the code "live" initially the first record I look at is displayed correctly. Once I move to another record, this goes out the window... I get random results where it will not change the backcolor to the proper color if >120 minutes has elapsed. Other times it changes the backcolor when there is <120 minutes elapsed. Sometimes no change in backcolor when it should or it will change color when it should not. I attempted to originally do this using TotalHours but met with the same results. It is random and is not consistent. I have worked on this for 2 days now with no difference in results. My thinking is there needs to be a way to "refresh" the rdResultDate & raResultDate info when each new record is loaded but I am unable to do that with my code knowledge.
The code must be able to take into account if a new date is present - ie raDate: 11/01/2016 and raTime: 23:46 and
rdDate: 11/02/2016 and rdTime: 03:00 - this would exceed 2 hours (or 120 minutes) and should read "True" and change the backcolor as it is over 2 hours (or 120 minutes).
However if the following were true:
raDate: 11/01/2016 and raTime: 23:46 and
rdDate: 11/02/2016 and rdTime: 01:00 this would not exceed 2 hours (or 120 minutes) and should read "False" and would not change the backcolor.
All of this code:
Dim Detention90 As String
Try
If elapsedR.TotalMinutes > 120 Then
Detention90 = "True"
Else
Detention90 = "False"
End If
Select Case Detention90.ToString
Case = "True" : tbRcvrDepartTime.BackColor = Color.LightPink
Case Else : tbRcvrDepartTime.BackColor = Color.White
End Select
Catch ex As Exception
'If a problem occurs, show Error message box
MessageBox.Show("Receiver Arrive Time & Depart Time Elapsed error" & vbCrLf & "Lines 1424-1434")
End Try
condenses down to just this:
Dim elapsedR As TimeSpan = rdResultDate.Subtract(raResultDate)
tbRcvrDepartTime.BackColor = If(elapsedR.TotalMinutes > 120, Color.LightPink, Color.White)
Not sure if it will directly address your issue, but it was a bit too much for a comment and I've found compacting code in this way is often extremely beneficial for tracking down difficult bugs.
But in this case, I suspect the main issue is parsing the datetime values... that you're not always parsing the DateTime value you expect from a given input string. Specifically, you have format string variables raDateFormat and rdDateFormat, but then call Date.Parse() such that these format variables are never used, and you are left at the mercy of whatever the default date format is for your thread, process, or system. If you're on a system that uses a d/m/y order as in the UK instead of the US-style m/d/y, you'll end up with some strange results. You probably want DateTime.ParseExact() instead.
My application contains a Datagridview, the user has the possibility to enter values like: Day, Time, how many hours did he work etc. The problem is that my second application calculates with this data. It has to be in a certain format.
Like time should be "09:15", but i noticed that some users are using "09,15" instead. Can you help me guys, I need a code that can check if a Range in Datagridview contains some " blacklisted char" and if yes, replaces it with the right one.
Thanks for all.
Do not save values as a string.
Validate input string straight in the needed type.
Then validated values pass to the second application.
In this case you don't need "blacklisted chars"
Private Sub DataGridView_CellValidating(sender As Object,
e As DataGridViewCellValidatingEventArgs)
If e.RowIndex < 0 Then Exit sub
Dim dgv As DataGridView = DirectCast(sender, DataGridView)
Dim columnIndexWithInteger As Integer = 2
Dim columnIndexWithDate As Integer = 3
Select Case e.ColumnIndex
Case columnIndexWithInteger
Dim temp As Integer
If Integer.TryParse(e.FormattedValue, temp) = False Then
e.Cancel = True
End If
Case columnIndexWithDate
Dim temp As Date
If Date.TryParse(e.FormattedValue, temp) = False Then
e.Cancel = True
End If
End Select
End Sub
In DataGridView, you have one handle that allows you to check the validity of an edited cell : CellValueValidating. It is called before the user change is taken into account (CellValueChanged event).
You can find example and explanation here :
- https://msdn.microsoft.com/en-us/library/ykdxa0bc(v=vs.110).aspx
- https://msdn.microsoft.com/en-us/library/7ehy30d4(v=vs.110).aspx
You can also have a look at CellValueChanged, CellValueValidated and CellEndEdit events.
I have two datetime pickers in vb.net that calculate the number of days between two dates and display in a message box the number of days. I want the number to display in a text box using vbnewline or any method but NOT to display in a messageBox
Private Sub btnCalculate_Click(sender As System.Object, e As System.EventArgs)Handles btnCalculate.Click
If True Then
Dim dt1 As DateTime = Convert.ToDateTime(DateTimePicker1.Text)
Dim dt2 As DateTime = Convert.ToDateTime(DateTimePicker2.Text)
Dim ts As TimeSpan = dt2.Subtract(dt1)
If Convert.ToInt32(ts.Days) >= 0 Then
MessageBox.Show("Total Days are " & Convert.ToInt32(ts.Days))
Else
MessageBox.Show("Invalid Input")
End If
End If
End Sub
Any input appreciated
Why not simply use Environment.NewLine
TextBox1.Text = "Total Days are"
TextBox1.AppendText(Environment.NewLine & Convert.ToInt32(ts.Days))
I think you are a bit confused. You can show the info in a TextBox, a MessageBox or a Label, but vbNewLine is just a constant that represents a line break, so you can use it with any of the previous controls.
Just put a TextBox usign the designer and then change the line
MessageBox.Show("Total Days are " & Convert.ToInt32(ts.Days))
with this:
YourTextBox.Text = "Total ......"
Good luck but do a little research the next time.
i am using the following expression to get the date :
SqlDataSource1.UpdateParameters("COLLECTIONDATE").DefaultValue = Date.Today.ToShortDateString
The output in the GridPanel in EXt shows only the date , that's what i want , but when i want to see the output in a textfield it shows me : "2013-05-20T00:00:00.000" , i don't know why the time is showing , any idea how to remove the time from showing in the textfield ?
You can do like this.
Date.Today.ToString("MM/dd/YYYY")
"MM/dd/YYYY" This is date format. You can also apply your date format.
Fo more detail on get formatted date visit this link. Click Here...
Not sure what GridPanel is, but you are setting value format. Instead you want to be setting column format of whatever UI element you have at your disposal for displaying data. My assumption here is that you are using a table there.
It might be datetime datatype
Try this to formatting on your datagriview ..
I assumed dgv as datagridview control ....
Private Sub dgv_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgv.CellFormatting
Dim sHeader As String = dgv.Columns(e.ColumnIndex).Name
If sHeader = "date" Then '--- change with your column name
If e IsNot Nothing Then
If e.Value IsNot Nothing Then
Try
e.Value = DateTime.Parse(e.Value.ToString()).ToLongDateString()
e.FormattingApplied = True
Catch ex As FormatException
e.Value = ""
End Try
End If
End If
End If
End sub