I've run into a problem with a program for my Visual Basic class that has me stumped. The assignment is a Guessing Game, I'm to create a private sub that generates a random number within the bounds of a user input (ie... 1 - 100). I seem to have this functional with the exception of telling the computer to guess lower. Currently if I press "Higher" the game continues, but if I press "Lower" the error is thrown with "minValue cannot exceed maxValue". If the output in the text box is higher than my lownum variable, why am I getting this error?
The bolded code is the code I have written, everything else was provided.
Public Class frmGuess
Dim highNum As Integer
Dim lowNum As Integer
Dim guess As Integer
Private Sub frmGuess_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MessageBox.Show("Lets Play a Game!")
'Fixed the grammatical error below - "Think of an whole number" is incorrect.
MessageBox.Show("Think of a whole number -- DON'T TELL ME!")
MessageBox.Show("Now give me a range you want me to guess in... like 1 to 100.")
lowNum = InputBox("Whats the starting value?", "Lowest Value")
highNum = InputBox("Whats the ending value?", "Highest Value")
lblTitle.Text = "I am guessing a number between " & lowNum & " and " & highNum & "."
newGuess()
End Sub
**Sub newGuess()
'
' ITS GONE! OH NO!
'
'New Guess Sub - Calculates a response based on the input from user and recalculates responses to guess the number.
'Setting New Variables
Dim random As New Random
'Generating Response
txtGuess.Clear()
txtGuess.Text = random.Next(lowNum, highNum + 1)
End Sub**
Private Sub btnLower_Click(sender As Object, e As EventArgs) Handles btnLower.Click
highNum = guess - 1
newGuess()
End Sub
Private Sub btnHigher_Click(sender As Object, e As EventArgs) Handles btnHigher.Click
lowNum = guess + 1
newGuess()
End Sub
Private Sub btnCorrect_Click(sender As Object, e As EventArgs) Handles btnCorrect.Click
MessageBox.Show("I win. I told you I was awesome.")
Close()
End Sub
Private Sub txtGuess_TextChanged(sender As Object, e As EventArgs) Handles txtGuess.TextChanged
End Sub
End Class
Figured it out, the program functions as expected.
Related
I have Project containing multi forms
main page and others inside main page
used next code to make confirm close in main page
Public Sub MyForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles MyBase.FormClosing
If MessageBox.Show("Do you want to close the form?", "Confirm", MessageBoxButtons.YesNo) <> DialogResult.Yes Then
e.Cancel = True
End If
End Sub
and want the confirm message to show in all forms not only main page !
Here is a process I use because MessageBox while it is nice I like to design my own.
You will see some variables in the code that look like this
Public gvalertType As String
Public gvRESEdit As String
These are declared in a Module
Now we need some code for the frmAlert You will use If and ElseIf to trap multiple errors. I will post a screen shot of the frmAlert
Private Sub frmAlert_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If gvalertType = "10" Then
btnNO.Visible = True
lblAI.Text = " Caution "
tbAlert.Text = "OK To Delete " & vbCrLf & vbCrLf & "NO Do NOT Delete"
End If
End Sub
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
If btnNO.Visible = True Then
gvRESDelete = "YES"
End If
Close()
End Sub
Private Sub btnNO_Click(sender As Object, e As EventArgs) Handles btnNO.Click
gvRESDelete = "NO"
Close()
End Sub
OK Now on the form and button click that calls the frmAlert.
Because you are changing forms this is why the variables are declared in a Module.
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
gvalertType = "10"
frmAlert.ShowDialog()
If gvRESDelete = "NO" Then
btnBack.Focus()
Return
End If
If gvRESDelete = "YES" Then
DeleteSiteData()
End If
End Sub
I have been trying to find out how to collect a string anywhere in a Listbox, I use Visual Basic 2010 and this is more of an request, but there is code I found so you fix the code I found or tell me me an another code to use.
I have tried using ListBoxName.Items.Contains but that did not work, I tried a lot of methods and it would be hard to say all of then at once.
' Split string based on space
Dim textsrtring As String = ListBox.Text
Dim words As String() = textsrtring.Split(New Char() {" "c})
Dim found As Boolean = False
' Use For Each loop over words
Dim word As String
For Each word In words
If ListBox.Items.Contains(word) Then
found = True
Exit For
End If
Next
MessageBox.Show(found)
They were no errors, the message box that appeared kept on telling me false and there is no string when I clearly put it in, no error messages.
You'll need an inner loop to see if each word is contained in your main listbox entry using String.Contains():
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim searchFor As String = TextBox1.Text.Trim
If searchFor.Length > 0 Then
Dim words As String() = searchFor.Split(New Char() {" "c})
Dim found As Boolean = False
Dim foundAt As Integer
' Use For Each loop over words
Dim word As String
For Each word In words
For i As Integer = 0 To ListBox.Items.Count - 1
If ListBox.Items(i).ToString.Contains(word) Then
found = True
foundAt = i
Exit For
End If
Next
If found Then
Exit For
End If
Next
If found Then
ListBox.SelectedIndex = foundAt
Label1.Text = "Search string found."
Else
ListBox.SelectedIndex = -1
Label1.Text = "Search string NOT found."
End If
Else
ListBox.SelectedIndex = -1
Label1.Text = "No search string."
End If
End Sub
I'm having a bit of trouble figuring out an assignment for my Visual Basic course. I am told to assume that a given text file is not in the \bin\Debug folder of my program, so I am trying to throw an exception error and get the correct path from the user via an inputbox but nothing appears to happen, or the variable isn't being set, I'm not entirely sure which. I have my code below, any hints as to why this will not work for me?
Thanks!
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim sr As IO.StreamReader
Dim age As Integer
Dim path As String
Try
sr = IO.File.OpenText("Ages.txt")
age = CInt(sr.ReadLine)
txtOutput.Text = "Age is " & age
Catch exc As IO.FileNotFoundException
path = InputBox("File Ages.txt not found." & vbCrLf & "Please enter the correct path to the file.", _
"Example: C:\Documents\My Text Files")
Catch exc As InvalidCastException
MessageBox.Show("File 'Ages.txt' contains an invalid age.", "Warning!")
Try
sr = IO.File.OpenText(path)
Finally
txtOutput.Text = "Age is " & age
End Try
Finally
Try
sr.Close()
Catch
End Try
End Try
End Sub
Your inner Try/Catch block should be inside the FileNotFoundException catch.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim sr As IO.StreamReader
Dim age As Integer
Dim path As String
Try
sr = IO.File.OpenText("Ages.txt")
age = CInt(sr.ReadLine)
txtOutput.Text = "Age is " & age
Catch exc As IO.FileNotFoundException
path = InputBox("File Ages.txt not found." & vbCrLf & "Please enter the correct path to the file.", _
"Example: C:\Documents\My Text Files")
Try
sr = IO.File.OpenText(path)
Finally
txtOutput.Text = "Age is " & age
End Try
Catch exc As InvalidCastException
MessageBox.Show("File 'Ages.txt' contains an invalid age.", "Warning!")
Finally
Try
sr.Close()
Catch
End Try
End Try
End Sub
An even better solution would be...
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim age As Integer
Dim path As String = "Ages.txt"
Dim fileFound As Boolean = False
While Not IO.File.Exists(path)
path = InputBox("File Ages.txt not found." & vbCrLf & "Please enter the correct path to the file.", _
"Example: C:\Documents\My Text Files")
End While
Using sr As IO.StreamReader = IO.File.OpenText(path)
If Integer.TryParse(sr.ReadLine, age) Then
txtOutput.Text = "Age is " & age
Else
MessageBox.Show("File 'Ages.txt' contains an invalid age.", "Warning!")
End If
End Using
End Sub
This will first check if the file exists, and continue looping until the user enter ones that does. This allows you to remove the FileNotFoundException catch.
This also uses Integer.TryParse to check if the value was casted correctly, allowing you to remove the InvalidCastException catch.
Lastly, opening the reader with a Using statement eliminates the need for a finally/nested try-catch block, as Using implements this internally.
I would bet that the exception being thrown is not an IO.FileNotFoundException, so your InputBox code is never being hit. OpenText can throw quite a few types of exception. There are several ways you can go about doing this without an exception (File.Exists comes to mind), but to continue on this route I would change your exception handling to something like this:
Catch exc as Exception
If TypeOf exc Is InvalidCastException Then
'...
Else
path = InputBox(....)
End If
End Try
I have created a simple VB 6.0 program to calculate day-to-day sales. I have converted this project into an .exe file where other users can run this program in their terminal to work with, but when they run this exe file they get above mentioned runtime error. Can anyone tell me how to overcome this error?
Dim myobject As Object
Private Sub Command1_Click()
Set myobject = Nothing
Adodc1.Recordset.AddNew
End Sub
Private Sub Command2_Click()
Adodc1.Recordset.Update
MsgBox "Your Record Updated Successfully!!", vbInformation
End Sub
Private Sub Command3_Click()
Text19.Text = Val(Text11) + Val(Text12) + Val(Text13) + Val(Text14) + Val(Text15)
End Sub
I'm writing a program that reads an input file that contains a line:
Scott Atchison,200,74
The file contains around 30 different lines of data. I know how to read in the file. After the file is read in it is split and then a calculation needs to be done (I know how to do that).
However, the problem that I have is the output file, I can get only the last line of the input file to the output file. This is what I have right now:
Public Class BMI
Dim data As String
Dim strName As String
Dim intWeight As Integer
Dim intHeight As Integer
Dim decBMI As Decimal
Private Sub btnInputFile_Click(sender As System.Object, e As System.EventArgs) Handles btnOpenFile.Click
'User chooses a file
OpenFile.ShowDialog()
'Choose a file name into a label
lblFileInput.Text = OpenFile.FileName
Dim inputFile As New IO.StreamReader(lblFileInput.Text)
Do While (inputFile.Peek() > -1)
data = inputFile.ReadLine
Dim fields() As String = data.Split(",")
strName = fields(0)
intWeight = fields(1)
intHeight = fields(2)
txtData.Text = txtData.Text & data & vbNewLine
Loop
FileClose()
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnSaveFile.Click
SaveFile.ShowDialog()
lblFileOutput.Text = SaveFile.FileName
Dim output As IO.StreamWriter
output = New IO.StreamWriter(lblFileOutput.Text)
output.WriteLine(data)
End Sub
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles Button1.Click
decBMI = (intWeight * 703 / (intHeight ^ 2))
data = strName & ", " & decBMI
End Sub
End Class
Wouldn't it write a line until all 30 lines are read, or Am I missing something, like a while loop? Any help would be appreciated.
It would be nice if you gave us a nice, executable, snippet of code, including declarations of all your variables. For instance, where is "data" defined. What is the relationship between both chunks of code? Are they in the same procedure?
The first thing I notice is that you are splitting each line, "data", into fields, saving them into variables, which you just ignore. You then append "data" to a text box.
Assuming that "data" is shared between the two chunks of code, then reason for your problem is that the value being written to the streamwriter is the last value of "data", which happens to be the last line that was read into it.