Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim password As String, ch As Char
Dim i As Integer
Dim valid As Boolean = False
While valid = False
password = InputBox("Please enter your password")
For i = 0 To password.Length - 1
ch = password.Chars(i)
If Not Char.IsLetterOrDigit(ch) Then
valid = True
Exit For
End If
Next
If valid Then
MsgBox("Your new password will be activated immediately")
Else
MsgBox("your password must contain at least one special symbol")
End If
End While
End Sub
Hello all, this program will check if there is a symbol within the password ,my question is in the statment (For i = 0 To password.Length - 1) its about (-1) why did we write -1,i understood everything except this -1 , thanks
Right i got it , you are right . Its because vb starts counting from 0 , so if i write 1234 this mean for vb 12345 and then we should remove the last digit by -1 and then we beocome 1234 as result. Thank you Hans Passant
Related
I am creating a program that is supposed to write text into a text file, and should be able to read specific lines from a text file in VB (so if i needed to read a specific name I could select line 5 and it would display in the textbox). I am able to read the text from the text file but I do not know how to control a specific line.
Here is my code:
Public Class Form1
Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
Dim writer As New System.IO.StreamWriter("/text.txt", True)
writer.WriteLine(txtFirstName.Text)
writer.WriteLine(txtLastName.Text)
writer.WriteLine("-------------------------------------")
writer.Close()
End Sub
Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
Dim reader As New System.IO.StreamReader("/text.txt")
Dim FirstName, LastName As String
FirstName = reader.ReadLine()
LastName = reader.ReadLine()
reader.Close()
txtFirstName.Text = FirstName
txtLastName.Text = LastName
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtFirstName.Clear()
txtLastName.Clear()
End Sub
End Class
Any help would be appreciated. Thanks!
You will have to read all lines up to the one you're interested in. For example:
Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To lineNumber - 1
If file.ReadLine() Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
' Succeded!
Return line
End Using
End Function
This is because lines of text are variable-length records, and there is no way to guess the exact file offset where a specific line begins — not without an index.
If you frequently need to load a specific line, you have some more options:
Load the complete text file into memory, e.g. by using File.ReadAllLines("Foobar.txt"). This returns a String() array which you can access by line number directly.
Create a line number index manually. That is, process a text file line by line, and fill a Dictionary(Of Integer, Integer) as you go. The keys are line numbers, and the values are file offsets. This allows you to .Seek right to the beginning of a specific line without having to keep the whole file in memory.
Try this:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim reader As New System.IO.StreamReader("C:\text.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
txtFirstName.Text = ReadLine(5, allLines)
txtLastName.Text = ReadLine(6, allLines)
End Sub
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
If you had a file with this:
Line 1
Line 2
Line 3
Line 4
My Name
My LastName
your name textbox will have 'My Name' and your LastName textbox will have 'My LastName'.
This is very simple, try this:
Dim strLineText As String
Dim intLineNumber As Integer
LineNumber=3
myLine = File.ReadAllLines("D:\text.txt").ElementAt(LineNumber).ToString
Yet another option
Private Function readNthLine(fileAndPath As String, lineNumber As Integer) As String
Dim nthLine As String = Nothing
Dim n As Integer
Try
Using sr As StreamReader = New StreamReader(fileAndPath)
n = 0
Do While (sr.Peek() >= 0) And (n < lineNumber)
sr.ReadLine()
n += 1
Loop
If sr.Peek() >= 0 Then
nthLine = sr.ReadLine()
End If
End Using
Catch ex As Exception
Throw
End Try
Return nthLine
End Function
i tried this and it works fine. using VB Express
content inside test.txt:
line1
line2
1
John
then in the form i add
textbox1
textbox2
label1
label2
and a button.
code inside the button:
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim myLine As String
Dim lineNumber0 As Integer
lineNumber0 = 0
Dim lineNumber1 As Integer
lineNumber1 = 1
Dim lineNumber2 As Integer
lineNumber2 = 2
Dim lineNumber3 As Integer
lineNumber3 = 3
TextBox1.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber0).ToString
TextBox2.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber1).ToString
Label1.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber2).ToString
Label2.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber3).ToString
End Sub
Here's a simple but effective solution:
Dim Reader As String = System.IO.File.ReadAllLines("C:\File.txt")(1)
MsgBox("Line 1: " + Reader)
The MsgBox should show the first line of C:\File.txt.
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'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.
I'm quite new to using VB, and I'm a beginner at programming, so I apologise for the poor/untidy code :P
I can't see what I'm doing wrong here. The program should get 3 numbers from the user, and those 3 numbers have to add up, then be divisible by 3 to be valid. Also, the number cannot be 1 less than the previous number. Failure to follow these 'rules' should result in a message box saying "INVALID SIDESWAP". I believe it is a problem with the MOD section, as no matter what I input, it always returns "VALID SIDESWAP". Any help will be greatly appreciated :)
Dim FirstNumber, SecondNumber, ThirdNumber As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = FirstNumber
TextBox2.Text = SecondNumber
TextBox3.Text = ThirdNumber
If (FirstNumber + SecondNumber + ThirdNumber) Mod 3 = 0 Then
If (FirstNumber - SecondNumber) <> 1 And (SecondNumber - ThirdNumber) <> 1 And (ThirdNumber - FirstNumber) <> 1 Then
MsgBox("VALID SIDESWAP")
Else
MsgBox("INVALID SIDESWAP 1")
End If
Else
MsgBox("INVALID SIDESWAP 2")
End If
End Sub
What heirich said is true, and will fix the problem, as long as you do enter Numbers in the textbox.
If you want to avoid any error the quick way is:
Firstnumber = val(Textbox1.text)
etc.
You are using Integers for firstnumber, val will also recognize Decimals, so you can use cdbl as well.
Firstnumber = cdbl(Textbox1.text)
But Empty Textboxes will generate an error, so use a combination
Firstnumber = cdbl(val(Textbox1.text))
I am trying to validate the input of a TextBox to make sure it is a Binary Number. What I have so far is:
Private Sub Command1_Click()
Dim b() As Byte
b = Text1.Text
If Not IsByte (b) Then
Text3 = "Wrong input"
Else
Text3 = "CRC is generated"
' checksum.Text = Text1.Text Xor Text2.Text
' Trans(2).Text = (Text1.Text) + (checksum.Text)
End If
Input in Text1 should only be accepting binary numbers, so only 1 or 0 should be allowed.
You can use Like here:
Private Sub Command1_Click()
If Len(Text1.Text) = 0 Or Text1.Text Like "*[!0-1]*" Then
MsgBox "bad binary string"
Else
MsgBox "good binary string"
End If
End Sub
This pattern is testing for "0 to many of anything, followed by one character not in the range 0 through 1, then 0 to many of anything."
Below is the code. Request you to kindly google before posting any questions to this forum.
'will only allow 0 and 1
Private Sub Text1_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case vbKey0 To vbKey1
Case Else
KeyAscii = 0
End Select
End Sub
' will validate if its numeric and you can further check for 0 or 1
Private Sub Command1_Click()
If Not IsNumeric(Text1.Text) Then
MsgBox "Please enter numbers only.", vbInformation
'you may also consider erasing it
Text1.Text = ""
End If
End Sub
Even i cant find the function to check binary data. But cant you just check like
If textbox1.text = 1 or textbox1.text = 2
I think you can also do with instr function.