VB 2013 Comparisons between user input and application memory - vb.net

I've got two questions.
Firstly how would you compare for examble "My.Settings.ListBox1" of type "System. Collections. Specialized. StringCollection" to the content of "ListBox1"?
I have a number of items on my form (ListBoxes, Checkboxes and TextBoxes) for which the user can input data and I have created a menu item called save to which they can save the data to application memory so that when the form reloads the user doesn't need to inpuit the data.
That being said I would like to compare the latest user input to what is in memory so that when the user tries to exit the program, if they haven't hit save and the input doesn't match memory then a flag is raised and I can ask them whether they'd like to save or not.
But I'm stumped on this comparison if anybody can help?
Second question is about what I want to do with the comparisons. For each comparison I thought I could increment a counter, so that if all the comparisons aren't met and the counter is less than the maximum number then I can raise a flag and the user can be prompted to save. Much in the fashion:
Dim saved As Integer
saved = 0
If My.Settings.TextBox2 = TextBox2.Text Then saved = saved + 1
If My.Settings.TextBox5 = TextBox5.Text Then saved = saved + 1
If My.Settings.TextBox9 = TextBox9.Text Then saved = saved + 1
If saved = 3 Then Me.Close()
Else
*Then I will deal with the prompts at this point.
I've not tested this. Just a last minute thought before bed. But my question is, is there a more eloquent way of doing this? I'm sure there is. But this is the best my newbie VB brain could come up with at this hour.
Thanks for any help and suggestions!

If you want to check if the textboxes didn't change you could do it like this.
Just start at textbox 1 if that's true then check textbox 2 , then 3 and so on.
As soon 1 is not true you can ask the user if he wants to save.
Put in the Public Sub SaveTextBox() everything you want to save.
I just used a button for it ,but of course you need to use it in the closing event.
Maybe this is not the best way but it works.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = My.Settings.TextBox1
TextBox2.Text = My.Settings.TextBox2
TextBox3.Text = My.Settings.TextBox3
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If My.Settings.TextBox1 = TextBox1.Text Then
If My.Settings.TextBox2 = TextBox2.Text Then
If My.Settings.TextBox3 = TextBox3.Text Then
Me.Close()
Else
SaveTextBox()
End If
Else
SaveTextBox()
End If
Else
SaveTextBox()
End If
End Sub
Public Sub SaveTextBox()
If MessageBox.Show("Save new settings ?", "My Application", _
MessageBoxButtons.YesNo, MessageBoxIcon.Question) _
= DialogResult.Yes Then
My.Settings.TextBox1 = TextBox1.Text
My.Settings.TextBox2 = TextBox2.Text
My.Settings.TextBox3 = TextBox3.Text
My.Settings.Save()
Me.Close()
Else
Me.Close()
End If
End Sub

Related

Can't get checking if file exists using textboxes to work

I've been racking my brain for days over this code and I just can't seem to get it working. I've researched and researched with no luck. I have four textboxes on my form. Two textboxes is a folder location and the other two textboxes are file locations. I'm trying to use a function that will return true or false telling if the files in the two textboxes exist or not. I don't see anything at all wrong with this code and it just won't work! I'm sure it's something simple I'm overlooking. Maybe someone else can spot it!
Private Function doesFileExist(folderPath, fileName) As Boolean
If IO.File.Exists(folderPath & "\" & fileName) Then
Return True
Else
Return False
End If
End Function
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If doesFileExist(txtCPU.Text, txtFileCPU.Text) And
doesFileExist(txtGPU.Text, txtFileGPU.Text) Then
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
Else
chkStart.Checked = False
chkStart.Text = "Start Monitor"
End If
Else
chkStart.Checked = False
MessageBox.Show("Please check directory & file locations!", "Error!", MessageBoxButtons.OK)
End if
End Sub
I want to mention that before I tried nested if statements on this I also tried to separate them both like so..
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If Not doesFileExist(txtCPU.Text, txtFileCPU.Text) And
Not doesFileExist(txtGPU.Text, txtFileGPU.Text) Then
chkStart.Checked = False
MessageBox.Show("Please check directory & file locations!", "Error!", MessageBoxButtons.OK)
Exit Sub
End If
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
Else
chkStart.Checked = False
chkStart.Text = "Start Monitor"
End If
End Sub
Both of these ways will show the messagebox if the application is ran with the checkbox checked on start up. Not only will it show the messagebox it also shows the messagebox twice! I've yet to figure that one out!
Your check file exists can be simplified... (It's been a while since I used VB so apologies for any syntax errors, I don't have an IDE to hand)
Function DoesFileExist(Folder as String, Filename As String) As Boolean
Return IO.File.Exists(IO.Path.Combine(Folder, Filename))
End Function
Re: Changing whether the "check" checkbox is set shouldn't perform the check itself - otherwise you only check when people click. (Incidentally, I'm guessing you're getting a message twice as code elsewhere ticks/unticks this checkbox, but it's only a guess).
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
PollTimer.Start()
Else
chkStart.Text = "Start Monitor"
PollTimer.Stop()
End if
End Sub
Finally... You need to define when your check will happen. Ideally, you'd want to use a FileSystemWatcher which will give you events when the file system changes, but you can also poll using a timer...
Private PollTimer As System.Timers.Timer
Then in your Form Main, do some initial timer setup...
...
PollTimer = New System.Timers.Timer()
PollTimer.Interval = 30000 ' Seconds
AddHandler PollTimer.Elapsed, AddressOf CheckExistsNow
PollTimer.Start()
...
And finally the code to run every time we want to make the check....
Sub CheckExistsNow(sender As Object, e As System.Timers.ElapsedEventArgs)
If Not DoesFileExist(txtGPU.Text, txtFileGPU.Text) Then
' Handle the missing file.
End if
End Sub

displaying label in different form with if else, vb.net

i have 2 forms. let's say form2 has a label that is not visible but with a particular "if" statement in form1, it will show up? here's my current code in form1 that isn't working:
Private Sub btnEnterPromoCode_Click(sender As Object, e As EventArgs) Handles btnEnterPromoCode.Click
Dim pcode As String
pcode = InputBox("Please enter any promo code below.", "Promo Code")
If pcode = "05567" Then
Dim resultz As Integer = MessageBox.Show("You have entered the 'Promo of the Week'.", "Promo Code Successful", MessageBoxButtons.OK)
frmCheckOut.lblFree.Show()
ElseIf pcode = "66795" Then
Dim resultx As Integer = MessageBox.Show("You have entered the 'Christmas Promo'.", "Promo Code Successful", MessageBoxButtons.OK)
frmCheckOut.lblFree.Show()
ElseIf pcode = "" Then
MessageBox.Show("You have entered a wrong code", "Promo Code Unsuccessful", MessageBoxButtons.OK)
Else
MessageBox.Show("You have entered a wrong code", "Promo Code Unsuccessful", MessageBoxButtons.OK)
End If
End Sub
sorry, kinda new with vb.net. thanks!! and anyway, in my code, checkout is the form2.
I suspect that frmCheckOut is a class name, not a reference to an instance of the class. When loading the second form, save a member-level or global reference to it. then use that reference in the call to Show.
This works for me:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim f As New Form2
f.Show()
f.Label1.BackColor = Drawing.Color.PeachPuff
f.Label1.Show()
End Sub
Having said that, I would have never thought to use f.Label1.Show() I would have used: f.Label1.Visible = True (I also normally don't use PeachPuff as a color, but that's a story for a different day).
As #JerryM already said, it looks like you are calling the form directly and not an instance of it (which is what I did in my example). That makes me think you may have to rethink the design of the application a little...

VB.net add line break after each loop

So I have been experimenting with VB.net (Windows Forms) to create a simple Ping Test app which pings the selected server and returns the elapsed time. I have declared a function to ping the address and then use a button to ping the server. The problem is that each time it pings, it only pings once and thus gives only one value. I would like to have a separate text box where the user enters the number of times they would like to ping the server for more accurate results.
Public Class Form1
Public Function Ping(ByVal server As String) As String
Dim s As New Stopwatch
s.Start()
My.Computer.Network.Ping(server)
s.Stop()
Return s.ElapsedMilliseconds.ToString
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim number As Integer = TextBox3.Text
For i = 1 To number
Try
TextBox1.Text = Ping(TextBox2.Text) & Environment.NewLine
Catch
MsgBox("Please enter a valid address", MsgBoxStyle.Critical, "Error")
End Try
Next
End Sub
End Class
I have tried using a loop to repeat the process and then return the results to a multi-line textbox for the user. Unfortunately it still only pings the address once and doesn't continue unless the ping button is clicked again, but then the first value is replaced by the next one. I believe the cause of the problem is that there should be a line break after each loop and I have tried using Enviroment.Newline but the problem persists. Any suggestions?
At the end I also would like to calculate the average ping of the results and expect to add all the ping values and divide by the number of times pinged. How would I get the results of the pings and add them?
Any help appreciated and excuse any spelling/grammatical errors.
In each loop you change the value of TextBox1 instead of appending the new value to the existing.
Optionally, you could also clear TextBox1 before starting the loop.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim number As Integer = TextBox3.Text
' Clear previous results
TextBox1.Text = String.Empty
For i = 1 To number
Try
' Append new result to existing ones
TextBox1.Text.AppendText(Ping(TextBox2.Text) & Environment.NewLine)
Catch
MsgBox("Please enter a valid address", MsgBoxStyle.Critical, "Error")
End Try
Next
End Sub

VB.Net How to close random choosed form

I am making some kind of quiz. I have made randomizer for questions. So when one question(form) pops up and when I click the right answer new form pops up, where you have one label and button to continue. I have made that when I click continue button next question(form) pops up, but i want that the previous form closes too, but i dont know how to name it or what to do.
Dim rn As New Random
TextBox1.Text = rn.Next(1, 4)
If TextBox1.Text = 1 Then
Form4.Show()
Form4.Timer1.Start()
End If
If TextBox1.Text = 2 Then
Form7.Show()
Form7.Timer1.Start()
End If
If TextBox1.Text = 3 Then
Form8.Show()
Form8.Timer1.Start()
End If
If TextBox1.Text = 4 Then
Form12.Show()
Form12.Timer1.Start()
End If
Hand over a reference to the question to the result form. Then you can call the Close() method on the previous question before opening the next one.
How about a routine that closes all your forms before opening a new one.
This isn't the best way - as your telling the forms to close even if they weren't open.
But it will do what you are asking.
Here is an example:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim rn As New Random
Dim randomForm As UInteger = rn.Next(1, 3) 'Random Form Number
TextBox1.Text = randomForm 'Store the Random Number here
closeQuestionForms() 'Routine called before opening others
Select Case randomForm
Case 1
Form2.Show()
'Do something else here
Case 2
Form3.Show()
End Select
End Sub
Private Sub closeQuestionForms() 'Closes the forms
Form2.Close()
Form3.Close()
MessageBox.Show("Closed Question Forms")
End Sub
Again, There is probably a better way which other answers might show you. But this way should work fine.

Variables to list box?

taking a VB class this term and I've been stumped on a problem I'm trying to figure out. We were asked to create a price calculator for movie titles at a movie rental place. Extra credit was storing them in a list and being able to print the list. I've gotten that far and now I want to go a step further and actually add titles to that list with an attached price. I figured the easiest way to do this would probably be with arrays but I don't have much experience working with arrays.
I was thinking something along the lines of storing each title(as its added) as well as the price in a variable to give a "Movie Title - $2.93" format in every line of the list box. For the sake of this problem I'm going to just post my full source code and that might make it easier to see what I'm trying to accomplish. ANY help would be MUCH appreciated. Thanks Stack overflow community!
A screenshot of my project can be viewed here: http://puu.sh/54SgI.jpg
Public Class Form1
'globablly declared because I might use them outside of btnAdd_Click event
Const decDiscount As Double = 0.9 '1-.10 discount = .9
Const decDVD As Decimal = 2D
Const decBlueray As Decimal = 2.5D
Const decDVDNew As Decimal = 3.25D
Const decBluerayNew As Decimal = 3.5D
Dim intCount As Integer
Dim decCost, decTotal As Decimal
Dim decDayTotal As Decimal
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AcceptButton = btnAdd
End Sub
Private Sub chkDiscount_Click(sender As Object, e As EventArgs) Handles chkDiscount.Click
If chkDiscount.CheckState = 1 Then
chkDiscount.Enabled = False
End If
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Display error when no title entered
If txtAdd.Text = "" Then
MessageBox.Show("Please enter a movie title and select the appropriate item details.", "Complete details", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
listMovies.Items.Add(txtAdd.Text)
listMovies.SelectedIndex = listMovies.SelectedIndex + 1
End If
'update list
'clear txtbox
txtAdd.Text = ""
'Decision Statements to calculate correct price
If radDVD.Checked = True Then
decCost = CDec(decDVD.ToString("c"))
If chkNew.Checked = True Then
decCost = CDec(decDVDNew.ToString("c"))
End If
ElseIf radBlueray.Checked = True Then
decCost = CDec(decBlueray.ToString("c"))
If chkNew.Checked = True Then
decCost = CDec(decBlueray.ToString("c"))
End If
End If
If chkDiscount.Checked = True Then
decCost = CDec((decCost * decDiscount).ToString("c"))
End If
'display cost
txtCost.Text = CStr(CDec(decCost))
'calc total
decTotal = CDec(decTotal + decCost)
'display total
txtTotal.Text = CStr(CDec(decTotal))
'clear chkNew every item added to list
chkNew.CheckState = 0
End Sub
'Public so summary message box can access variable
Public Sub btnFinish_Click(sender As Object, e As EventArgs) Handles btnFinish.Click
'Add +1 to counter & update txtCounter
intCount = CInt(Val(intCount) + 1)
'add to day total
decDayTotal = CDec(Val(decDayTotal) + decTotal)
'Set Everything back to empty/enabled
chkDiscount.Enabled = True
chkDiscount.CheckState = 0
chkNew.CheckState = 0
txtAdd.Text = ""
txtCost.Text = ""
txtTotal.Text = ""
decTotal = 0
decCost = 0
'Instead of clearing radios each time, a more desirable result would be to have DVD always set back to the default checked radio
radDVD.Checked = True
radBlueray.Checked = False
listMovies.Items.Clear()
End Sub
Private Sub btnSummary_Click(sender As Object, e As EventArgs) Handles btnSummary.Click
If decTotal > 0 Then
MessageBox.Show("Please finish your current order before viewing a daily summary.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
MessageBox.Show(("Your total cutomer count is: " & intCount) + Environment.NewLine + ("Your total sales today is: $" & decDayTotal), "Daily Summary", MessageBoxButtons.OK)
End If
End Sub
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
listMovies.Items.Remove(listMovies.SelectedItem)
End Sub
I wont go very far here because you need to do the work. But, I would start with a class:
Public Class Movie
Public Title As String = ""
Public Cost As Decimal
' prevents you from adding a movie without critical info
Public Sub New(ByVal t As String, ByVal c As Decimal)
Title = t
Cost = c
End Sub
End Class
This would hold the info on one movie title rental, and keep it together (and can be added to in order to print exactly as you showed) . The plan (to the extent I understand what you are after) would be to create one of these for each movie rented and add it to a List(Of Movie) this is more appropriate than a Dictionary in this case.
To create a movie:
Dim m As New Movie(theTitle, theCost)
Things I would do:
You did a good job of declaring numerics as numbers. Fix the code that converts it to string and back to numeric. (edit your post)
You can use the Movie Class to populate the "Shopping Cart" listbox alone; at which point, listMovies.Items would BE the extra credit List. But it wouldnt hurt to use/learn about List (Of T). (BTW, does 'print' mean to paper, on a printer?)
What are you doing with chkDiscount? If they check it, you disable it (and never enable). Did you mean to disable the New Releases check? In THAT case, arent they really a pair of radios too?
Either way, CheckChanged is a better event for evaluating and there is no reason to manually set the check state for the user that happens by itself.
Check out List(of T) and HTH
A good thing to think about when doing assignments like this (particularly when learning your first language) is to think of the algorithm (the step you need to get to your goal).
1st, determine all the steps you need to get to your goal.
2nd, and I think this is the more import point for your question, figure out what order the steps need to be in (or better yet, what order they are most efficient in).
In your case I think that you are kind of ice skating up hill by adding the name of the movie to the list first, and then trying to add the price to the line later. Unless that kind of functionality was requested as part of the assignment I would require the user to enter both the name AND the price before accepting either (just like you do with the name currently). Like thus:
If txtAdd.Text <> "" AND txtCost.Text <> "" Then 'requiring both fields to not be null
''add moive code
Else
''MessageBox.Show("Yadda Yadda Yadda")
End If
I agree with Plutonix that creating a class, while overkill in your case, is a good idea, as it will give you practice for when it WILL be appropriate. Once you have that a class of Movie, you can then create lists of Movie(s) like this:
Dim MovieList as new List(of Movie)
So then, each time you press the btnAdd button, you can pass the values to a movie AND add it to the list.
Dim m As Movie
Dim MovieList as new List(of Movie)
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Display error when no title entered
If txtAdd.Text <> "" And txtCost.Text <> "" Then
myMovie = New Movie(txtAdd.Text, txtCost.Text)
myMovieList.Add(myMovie)
listMovies.Items.Clear()
For Each X As Movie In myMovieList
listMovies.Items.Add(X.DisplayMovie)
Next
Else
MessageBox.Show("Please enter a movie title and select the appropriate item details.", "Complete details", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
'Other Code
End Sub
Note the line ListMovies.Items.Add(X.DisplayMovie) I added a function to the class Movie (seen below) so that it will do the formatting as you suggested.
Public Function DisplayMovie()
Return Title & " - $" & Cost
End Function
This will get you much of the way. Try to extrapolate what Plutonix and myself have explained to further refine your code. For instance, try encapsulating your adjusted price calculation in its own function so you can call it from anywhere.