VB.NET realtime clock in a textbox - vb.net

How can I make it so that when I load the form a textbox will show me (dd/mm/yyy hh:mm:ss) format clock that is actually moving and is synced with the system?
I tried googling it but so far couldn't find anything that works. Most answers dealt with making labels into clocks but I figured it's the same with textboxes and tried doing what they said with no results. It shows me the time but it's just the time when the form loaded not an actual moving clock. I think most of the answers I found on google are dealing with older versions of VB that's why I can't get it to work.
P.S. I'm just learning coding so the simpler the code the better. Many step by step (like I'm 5) comments are appreciated as well. Thank You

Add a Timer to your form, and add this code to it's tick event.
Textbox1.text = Format(Now, "yyyy-MM-dd hh:mm:ss")
You now have a textbox which tells you the current date and time.
Don't forget to enable your timer, though!

Try to put your time and date string inside a timer. this is how it looks like:
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
TimerText.Text = TimeString
DaterText.Text = DateString
End Sub
It will surely show you a moving/real time clock that was sync to your computer. :)

Related

Textbox and currency formatting

I'm trying to format two specific text boxes to show up as Sq. ft. (txt.Squareft.Text) and US currency (txtTotalprice.Text) after a calculation has been made in Visual Studio 2019 as a Windows Form Application and using visual basic code. I am using .NET framework v4.7.2 and utilizing Windows 10. The way it runs now, the numbers that show up in the textboxes are just numbers without the added Sq. ft. at the end and no currency formatting. I will also add that I am very new to VB and programming in general. Any help or suggestions?
Option Explicit On
Option Infer Off
Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
'Variables
Dim decTotalprice As Decimal
Dim decLength As Decimal
Dim decWidth As Decimal
Dim decPrice As Decimal
Dim decSquareft As Decimal
Decimal.TryParse(txtLength.Text, decLength)
Decimal.TryParse(txtWidth.Text, decWidth)
Decimal.TryParse(txtPrice.Text, decPrice)
Decimal.TryParse(txtSquareft.Text, decSquareft)
txtTotalprice.Text = decTotalprice.ToString("C2")
txtSquareft.Text = decSquareft.ToString("N2") & " Sq. ft."
' Calculate the square feet and total price
txtSquareft.Text = txtLength.Text * txtWidth.Text
txtTotalprice.Text = txtPrice.Text * txtSquareft.Text
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
' Clears all the text fields with button click
txtLength.Clear()
txtWidth.Clear()
txtPrice.Clear()
txtSquareft.Clear()
txtTotalprice.Clear()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
' Exits the form
Me.Close()
End Sub
End Class
There are two primary issues here and I feel like I bring them up at least ten times a day. Firstly, you are trying to write code without knowing what that code has to do. You've considered the end result but not the steps to get there. If you had done that then it would be obvious that your code doesn't what it's supposed to. Secondly, you clearly haven't debugged your code, which is the first thing anyone should do when they don't get the expected result. That would also let you see that your code doesn't make sense IF you considered what each line is supposed to be doing as it does it.
If this was a manual task, you would get the input from the user, perform the calculation, then display the result. Is that what you're doing here? No, it is not. First you get the user input. That's a start, but you're doing it wrong. As it stands, you would end with zero for any invalid input but you're just ignoring that. The next thing you do is display the formatted output that you haven't even calculated yet. If you had debugged, you'd have seen that both decTotalprice and decSquareft are zero at that point. You finally do the calculations, but with the raw text input instead of the numbers you already parsed, and then you display the results unformatted. You've even got a comment in your code that says that you're doing the calculation AFTER you've displayed the formatted output.
Stop writing code and think about what the required steps are to get to your desired result. Parse the user input, perform the calculations with the numeric data and not the unparsed text, then display those results with formatting. Once you have a clear idea of what you have to do AND tested that manually, then you can write code to implement that algorithm, rather than some vague idea in your head that involves a final result and little else.
You're certainly not the only person who makes these mistakes but they are elementary mistakes. They happen partly because of bad teaching in some cases, but they also happen because everyone wants to jump into the part that is sexy and fun, i.e. writing the code, but they don't want to do the harder but just as important part of considering what the code actually has to do. When they don't get the expected result, they throw their hands up without ever really having tried to fix it. If you haven't tried to understand what the code has to do, you can't have tried to make it do that.

VB.Net - Manage errors label

I'm working on visual studio 2015 and I'm working on a classic subscribing form.
I want to generate error labels when the user type wrong password, the wrong pseudo, etc. But I can work on it myself.
But when I write those error labels and set their visible at false in "Dev mode", I have to juxtapose those labels if I want my labels at the same place, and it's not what I want when I have many errors to manage on one textBox for example.
Is there a solution to gererate those labels, without write them before playing with hide() or show() ?
Here is the screenshot in order to illustrate my problem.
It's not really a problem itself, but It's not practical when I'm develop many errors.
Sorry for my english, I hope you understood my problem, I can give you more details =)
Have a nice day full of code !
Here the button code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text <> "Password" Then
Label2.Text = "Your answer is wrong"
End If
End Sub
This is what it looks like:

Why is basic time/date output taking two seconds to display?

What I have:
I'm displaying the current time and date (real-time) at the bottom of a form using a timer element.
I'm using two labels to display the time and date respectively.
What I need:
I need the time and date labels to display as instantly as everything else.
My problem:
There is a two second delay in the displaying of the time and date labels.
My code:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Format time and date labels.
TimeMain.Text = Format(Now, "hh:mm:ss")
DateMain.Text = Format(Now, "dddd, d/MM/yyyy")
End Sub
Note: The above is preceded by a Form_Load sub that simply defines a default accept button. The above is followed by 5 by five short subs.
Edit:
Though the steps for reproducing the problem have already provided in the comments I've been requested to reiterate here. The only difference between the two code blocks posted in this question is that I've left the label text at default to spare the reproducer having to type anything.
Drag two labels and a timer onto a new form and use the following code:
Public Class Form1
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Format time and date labels.
Label1.Text = Format(Now, "hh:mm:ss")
Label2.Text = Format(Now, "dddd, d/MM/yyyy")
End Sub
End Class
For the timer's properties, Enabled is defined as True and Interval as 1000.
I know this isn't exactly an answer but this is too long to fit in a comment. Also read here for a little more information on timers:
Why are .NET timers limited to 15 ms resolution?
Does the System.Windows.Forms.Timer run on a different thread than the UI?
Timer elapsed events from what i understand (which could very well be wrong) aren't guaranteed to fire exactly when the time has elapsed, it's more of... put it in queue to fire once the timer has elapsed.
Imagine your application/timer started at "00:00:01.999" and your label states "00:00:01" as the current time.
Exactly 1000 MS later you're at "00:00:02.999 and the elapsed event fires, completing at "2014-01-01 00:00:03.0045" and your label is updated to "2014-01-01 00:00:03" - you've already "lost" a second here.
You could try setting your interval to something lower than one second (say 750) which would get you a potentially more accurate looking counter. Additionally, ensure you're setting the timer labels on form load. I've not worked very much with timers and i'm having trouble finding the article i was reading earlier but you might need to worry about UI locking depending on the timer type used (there are apparently 4 timer classes in the .net framework.) Perhaps someone else can expand on that though, I don't know much about winforms.

Save Excel file in every 2 second without using macro

I want to save an excel at every 2 seconds. Data is updated in this excel through DDE and want to read this data every 2 seconds. Unfortunately this data is not saved on hard disk.
I am aware of macro which can be used to save file after specified point of time but do not want to use macro.
Since data is updated frequently in this sheet through DDE (at every 100 MS) so sheet change event triggers too often.
Below is the code which i am trying but not getting success.
Dim ctme, ptme As Integer
Private Sub Workbook_Open()
ctme = Second(Now)
ptme = ctme - 2
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
ctme = Second(Now)
If (ctme - ptme) = 2 Then
Me.Save
ptme = ctme
End If
End Sub
Please help
Nidhi, people here are trying to help you and you need to understand that no one has the access to your brain to understand what you actually meant to ask. So it is quite natural to ask questions to understand the issue clearly before suggesting any answer. The people here, get equally frustrated when they are unable to understand a simple question, the time they spend could have been easily saved, had the person spent a little extra time in explaining the things better. So giving credit to those who are trying to help you, will not harm at all.
Ok, coming back to your question. I may be wrong, but I think that SheetChange event is not fired on DDE update. Please correct me if I am wrong.
The next option can be Application.OnTime functionality.
Write the following code in Workbook Open Method:
Private Sub Workbook_Open()
Dim currentTime As Date
currentTime = DateAdd("s", 2, Now)
Application.OnTime currentTime, "SaveFile"
End Sub
Then Add a new Module and add the following Function there in new Module:
Public Sub SaveFile()
ThisWorkbook.Save
Dim currentTime As Date
currentTime = DateAdd("s", 2, Now)
Application.OnTime currentTime, "SaveFile"
End Sub
The above code will create a timer which would run every two seconds to save your file. There are pros and cons for this approach, but it's Excel's best possible Timer functionality. Let me know if you have any questions.
Thanks,
Vikas
(this is totally away from the OP tags but just thought I'd put forward a possible alternative)
Create a small .NET console application.
User one of the Timer objects available to create this timed loop you require.
Then using a reference to Excel Interop library on each sweep of the loop it looks like you might need to open this workbook, save it, and then close it again .....depending on the calculations within the book and the size of the Excel file is it physically possible on your machine to open/calculate/save within 2 seconds?

Decimal.TryParse is failing on TextBox.Leave and TextBox.LostFocus

This has got to be one of the most frustratingly stupid bugs I have ever encountered, and I just want to see if anybody else has run into this before.
Here's the deal. I have a TextBox in a Windows Forms application in VB 2008 (.NET 3.5) where a user can key an estimate amount. I am allowing them to key dollars and cents, and I want to round to the nearest dollar. The original code had the rounding down when the data was written back to a table, and that worked fine - I have this code in a "Save" routine that fires when the user moves to a different screen or record:
Dim est As Decimal : Decimal.TryParse(txtEstimateAmount.Text.Trim, est)
Dim estimatedAmount As Integer = Math.Round(est)
I decided that it might be nice to actually do the rounding as soon as they leave the field instead, so they're not surprised when they reload the screen and find that 1822.60 is now 1823. So I took the exact same code and added it to the TextBox.Leave event handler. And the weirdest thing happened: instead of the variable est being populated with 1822.60 after the parse, it gets set to -1! What the...?
Debugging the handler shows that the value goes into the parser correctly, and if I do the parsing manually via the Immediate window, it parses correctly, but when I let the code do it, it invariably gets set to -1. What's even weirder is that any number gets parsed as -1, not just decimals, and any non-number gets parsed as 0 (which is correct).
Has anybody else ever run into this before? I tried moving the code to the TextBox.LostFocus event instead, but with the same results. I have no idea what in the heck is going on, and obviously there are workarounds galore for this, but it just makes no sense whatsoever.
EDIT: Here's the full event handler (current behavior for which is to put -1 in the TextBox):
Private Sub txtEstimateAmount_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtEstimateAmount.Leave
' Take any dollars-and-cents amount and round to the nearest dollar
Dim est As Decimal
est = Decimal.TryParse(txtEstimateAmount.Text.Trim, est)
txtEstimateAmount.Text = If(est <> 0, Math.Round(est).ToString(), String.Empty)
End Sub
First off, you really need to do this with a Validating event handler so that you can catch junk and avoid ignoring the return value of TryParse. Like this:
Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
Dim est As Decimal
If TextBox1.Text.Length = 0 then Exit Sub '' optional
If Not Decimal.TryParse(TextBox1.Text.Trim, est) Then
e.Cancel = True
TextBox1.SelectAll()
Else
TextBox1.Text = est.ToString("N0")
End If
End Sub
Explaining -1 is difficult. TryParse normally writes 0 if it cannot parse the text. Watch out for changing the UI thread's CurrentCulture property. And any changes made to the format settings in Control Panel + Region and Language applet.
I don't think the code you've posted is the code you're running. What is happening is:
Dim est As Decimal = Decimal.TryParse(txtEstimateAmount.Text.Trim, est)
Dim estimatedAmount As Integer = Math.Round(est)
I would do a clean and a rebuild or try rewriting it in a different format, maybe with a boolean to get the result of the tryparse.
EDIT now that I've seen your actual code. You are indeed putting the true/false from the tryparse result into the est decimal. Delete the est=. Est gets loaded because it is passed by reference into tryparse.