How can i shorten this code? - vb.net

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Label1.Text.Length = 13 Then
Label1.Text = "Working magic."
ElseIf Label1.Text.Length = 14 Then
Label1.Text = "Working magic.."
ElseIf Label1.Text.Length = 15 Then
Label1.Text = "Working magic..."
ElseIf Label1.Text.Length = 16 Then
Label1.Text = "Working magic"
End If
End Sub
The code basically acting as a progressive string, where every 500 milliseconds a dot will add to the string, until 3 dots where it resets.
If I wanted to do more dots then it would be nice to automate the process, instead of writing an infinite number of lines of code.

If you want to shorten your code you could do something like this:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
(Label1.text += ".").Replace("....","")
End Sub
However I'm convinced that shorter is not always better!
Edit: Sorry my mind goes straight to c#, here is some VB::
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.text = (Label1.text + ".").Replace("....","")
End Sub

Pseudo code:
len = Label1.Text.Length - 12
str = "Working magic"
while(len>0 && len<4){
str = str & "."
len--;
}
Label1.Text = str

Pseudo code that takes into account the variable number of dots in a row.
final NUM_DOTS = 3 //this is your variable number of dots
len = Label1.Text.Length - 12
str = "Working magic"
numDots = NUM_DOTS
while(len){
if (numDots == 0) {
str = str.substring(0, str.length-NUM_DOTS);
numDots = NUM_DOTS;
}
else {
str = str & "."
len--;
numDots--;
}
}
Label1.Text = str

easy, console apps demo
Module Module1
Sub Main()
Console.WriteLine(Magic(New String("A"c, 13).Length))
Console.WriteLine(Magic(New String("A"c, 14).Length))
Console.WriteLine(Magic(New String("A"c, 15).Length))
Console.WriteLine(Magic(New String("A"c, 16).Length))
Console.Read()
End Sub
Private Function Magic(ByVal len As Integer) As String
Dim result = "Working magic"
Select Case len
Case 13 To 15
result = result & New String("."c, len - 12)
End Select
Return result
End Function
End Module

Consider using animated GIFs like those generated here: http://www.ajaxload.info/
Try Google Search for more options: "animated gifs generator"
Just use the GIF in a picture box and use .Enable/.Visible to manage.
The animation can be stalled if the main thread is busy - probably true for the above cases as well.

Keep the count of dots to print as a global variable, then at every call of the timer event increment this value and reset it if it reaches the upper limit.
Create a string of dots based on the current count and append it to the static label
Private dotCount As Integer = 0
Const MAX_DOTS = 3
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
if dotCount > MAX_DOTS Then
dotCount = 0
End If
Label1.Text = "Working magic" & new String(".", dotCount)
dotCount = dotCount + 1
End Sub
If you want to print more dots, just change the constant used as upper limit (MAX_DOTS)

Related

Click Button and Count Vb.Net

I want to Count how many times I click a button and display the number, but the format should be like: 0001 if reach 9999 restart to 0001 again and count till 9999.
I tried:
Private ButtonClickCount As Integer = 0
ButtonClickCount += 1
Label5.Text = "0000" & ButtonClickCount
And
Label5.Text = "0000" + Val(Label5.Text) + 1
This was the dumbest way I tried.lol
And the result was disapointing.
Is there any easy way to do it?
If you use a Static variable for the count, you can keep it in the button click event handler. (Static variables aren't used all that often, but it works here, assuming you don't need the variable anywhere else.)
If you check if the counter has reached 10000, you can set it back to 1.
You can format the number in the .ToString method.
Perhaps something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static clickCount As Integer = 0
clickCount += 1
If clickCount = 10000 Then
clickCount = 1
End If
lblClickCount.Text = clickCount.ToString("0000")
End Sub
You could use the Format command, which controls how many zeroes you want in the output:
Dim ButtonClicks As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ButtonClicks += 1
Label1.Text = Format(ButtonClicks, "0000")
End Sub
Dim ButtonClicks As Integer = 0
Private sub Button1_click(sender as object, e as EventArgs) handles Button 1.click
Buttonclick +=1
If buttonclick ="9999" then
Buttonlclick=1
Endif
Label1.text =format(Buttonclick, "0000")
End sub
You will need to keep track of the counter somewhere, in this case I would suggest storing the counter in the control's Tag property (documentation). In your button's click event, you would do the following:
Get the Tag
Convert the value to an Integer
Increment the value by 1
Check if the new value is greater than 9999
Optionally reset the value to 1 if 4 is true
Set the Text of the Button to the formatted result
Set the Tag of the button to the new value
Here is an example:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim clickedButton = DirectCast(sender, Button)
Dim tagValue = clickedButton.Tag
If (tagValue Is Nothing) Then
tagValue = 0
End If
Dim conversion As Integer
If (Not Integer.TryParse(tagValue.ToString(), conversion)) Then
conversion = 0
End If
conversion += 1
If (conversion > 9999) Then
conversion = 1
End If
clickedButton.Text = converstion.ToString("0000")
clickedButton.Tag = conversion
End Sub
Well, sorry guys, just realized that I could use the PadLeft function... And worked fine.
ButtonClickCount += 1
Label5.Text = ButtonClickCount.ToString().PadLeft(5, "0")
But Still don't know if it reaches 9999 will restart from 0001

How can I get ten numbers and displays the biggest and lowest one?

sorry I'm a newbie and I'm trying to write a program to get ten integers from user with a an Inputbox or Textbox and displays the biggest and lowest one in a label with visual basic. I'll be appreciated if you help me out with this.
Thank you. this is my solution. I don't know how to compare these ten numbers with each other.
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers
Max = 0
i = 1
While (i <= 10)
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers
i = i + 1
End While
lblresult.Text = Container
End Sub
conceptually speaking you should use a List(Of Integer) or List(Of Double), perform the loop 10 times adding the value into the list.
Suppose this is our list
Dim container As New List(Of Integer)
To get input
Dim userInput = ""
Dim input As Integer
userInput = InputBox("please enter a number", "Enter a number")
If Integer.TryParse(userInput, input) Then
container.Add(input)
End If
After the loop
Console.WriteLine($"Min: {container.Min()} Max: {container.Max()}")
Does this make sense to you ?
Edit, based on asking for Windows Forms example.
You could do the following instead of a InputBox, requires a label, a button and a TextBox.
Public Class MainForm
Private container As New List(Of Integer)
Private Sub CurrentInputTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles CurrentInputTextBox.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
CurrentLabel.Text = "Enter number 1"
End Sub
Private Sub ContinueButton_Click(sender As Object, e As EventArgs) _
Handles ContinueButton.Click
If Not String.IsNullOrWhiteSpace(CurrentInputTextBox.Text) Then
container.Add(CInt(CurrentInputTextBox.Text))
CurrentLabel.Text = $"Enter number {container.Count + 1}"
If container.Count = 10 Then
ContinueButton.Enabled = False
CurrentLabel.Text =
$"Count: {container.Count} " &
$"Max: {container.Max()} " &
$"Min: {container.Min()}"
Else
ActiveControl = CurrentInputTextBox
CurrentInputTextBox.Text = ""
End If
End If
End Sub
End Class
I really didn't want to do your homework for you but I was afraid you might be hopelesly confused.
First let's go over your code. See comments
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers 'Don't declare variables without an As clause
Max = 0 'Max is an object
i = 1 'i is and object
While i <= 10 'the parenthesis are unnecessary. You can't use <= 2 with an object
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers 'Container is an object; you can't use & with an object
i = i + 1 'Again with the object i can't use +
End While
lblresult.Text = Container
End Sub
Now my approach.
I created a List(Of T) at the Form level so it can be seen from different procedures. The T stands for type. I could be a built in type or type you create by creating a Class.
The first click event fills the list with the inputted numbers. I used .TryParse to test if the input is a correct value. The first parameter is a string; the input from the user. The second parameter is a variable to hold the converted string. .TryParse is very clever. It returns True or False base on whether the input string can be converted to the correct type and it fills the second parameter with the converted value.
The second click event loops through the list building a string to display in Label1. Then we use methods available to List(Of T) to get the numbers you desire.
Private NumbersList As New List(Of Integer)
Private Sub FillNumberList_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer
While i < 10
Dim input = InputBox("Please enter a whole number")
Dim inputInt As Integer
If Integer.TryParse(input, inputInt) Then
NumbersList.Add(inputInt)
i += 1 'We only increment i if the parse is succesful
End If
End While
MessageBox.Show("Finished Input")
End Sub
Private Sub DisplayResults_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label1.Text = "You input these numbers "
For Each num In NumbersList
Label1.Text &= $"{num}, "
Next
Label2.Text = $"The largest number is {NumbersList.Max}"
Label3.Text = $"The smallest number is {NumbersList.Min}"
End Sub

Add a completely different line with every button click

Complete noob to vb.net (and programming in general) here, all I really want is every time I click a button, the number in the textbox is added by 1 but the new number shows up on the next line. Tried to google this a hundred times but nothing really helped.
I don't want to use loops as I don't want all numbers to show up at once, only for the added number to show up after clicking a specific button (on a new line).
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim txtoutput As String = ""
Dim a As Integer = 1
txtoutput &= "the value of a =" & a & Environment.NewLine
a = a + 1
TextBox1.Text = txtoutput
End Sub
You are replacing the Text, you want to append a new line, so you need to do:
Private a As Int32 = 0
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
a += 1
Dim newLine = $"the value of a = {a}"
TextBox1.Text = TextBox1.Text & Environment.NewLine & newLine
End Sub
You also have to use a field and not a local variable if you want to retain the old value and increment it. Otherwise it is reset always to it's inital value.
Please try to change dim a to static a
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim txtoutput As String = ""
Static a As Integer = 1
txtoutput &= "the value of a =" & a & Environment.NewLine
a = a + 1
TextBox1.Text = txtoutput
End Sub

How do I count how many guesses it takes to get the correct number in Visual Basic?

I have been struggling with this code for a while. I'm trying to make it so after the user gets the number right, the program counts how many tries it has taken them to get the number right. How can I do this?
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
'SELECTS THE SECTET NUMBER
Randomize() 'WITHOUT rANDOMIZE, THE SAME SEQUENCE OF NUMBERS APPEARS EACH RUN
secretNumber = Int(Rnd(1) * 1000 + 1) 'picks a random nubmer between 1 and 1000
'sets the initial prompts
Me.lblLow.Text = 1
Me.lblHigh.Text = 1000
Me.txtGuess.Focus()
Dim count As Integer
btnEnterGuess.Enabled = True
btnStart.Enabled = False
Dim i As Integer
For i = 1 To count
count = count + 1
Next i
Do
count = count + 1
Loop Until count = secretNumber
MessageBox.Show("It took you " & i - 1 & " tries to get the number correct.")
End Sub
I threw this piece of code togeather, hopefully it will help.
Something to note when writing this kinda code, is that all this code is running on a single thread (unless you declare it otherwise). This means your program will become unresponsive when you run that for loop.
Public Class Form1
Dim count As Integer = 0
Dim answer As Integer = 0
Dim GameRunning As Boolean = True
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message,
ByVal keyData As System.Windows.Forms.Keys) _
As Boolean
'Gets all keystrokes on the fourm
If GameRunning Then
'converts keystroke to key ID and tests to see if the keystroke is the ENTER key
If msg.WParam.ToInt32() = CInt(Keys.Enter) Then
'try catch to prevent crash if text in entered
Try
If txtAnswer.Text = answer Then
MessageBox.Show("Congratz! It took you " & count & " tries to guess the number!")
Else
txtAnswer.Text = ""
count = (count + 1)
End If
Catch ex As Exception
End Try
End If
End If
'update label to show tries
lblTries.Text = "Tries: " & count
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
Private Sub SetupOnLoad() Handles MyBase.Load
Reset()
End Sub
Public Sub Reset()
count = 0
Randomize()
answer = Int(Rnd(1) * 1000 + 1)
txtAnswer.Text = ""
lblTries.Text = "Tries: " & count
GameRunning = True
End Sub
'the Reset() code is ran on the program launch and when you press the button to prepare the game.
Private Sub Reset_Game() Handles BtnReset.Click
Reset()
End Sub
End Class
This code gets the user input in the text box. When the user presses ENTER, the program tests to see if its the correct number.
Hope this helped!
I will try something like this, randomize need to be placed outside of the click
Public Class Form1
Dim count As Integer = 0
Dim answer As Integer = 0
Private Sub btnStart_ClicK(sender As Object, e As EventArgs) Handles btnStart.Click
Randomize()
answer = Int(Rnd(1) * 1000 + 1)
btnStart.Enabled = False
btnGuess.Enabled = True
End Sub
Private Sub btnGuess_Click(sender As Object, e As EventArgs) Handles btnGuess.Click
count += 1
If answer = TextBox1.Text Then
MessageBox.Show("It took you " & count & " tries to get the number correct.")
btnStart.Enabled = True
btnGuess.Enabled = False
count = 0
answer = 0
Else
TextBox1.Text = ""
End If
End Sub
End Class

VB.NET Read text file line by line and set every line in textbox with button clicks

hello i want to read text file line by line and set every lien in textbox eash time i click the button
this is my code and working fine. but i looking for easy way to read large text that has more thean 5 lines ?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Static count As Integer
count = count + 1
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
Dim readLines() As String = IO.File.ReadAllLines(myFile)
If count = 1 Then
TextBox1.Text = readLines(0)
End If
If count = 2 Then
TextBox1.Text = readLines(1)
End If
If count = 3 Then
TextBox1.Text = readLines(2)
End If
If count = 4 Then
TextBox1.Text = readLines(3)
End If
If count = 5 Then
TextBox1.Text = readLines(4)
End If
If count = 6 Then
TextBox1.Text = readLines(5)
End If
End If
End Sub
I think you need to read the file just one time when you load your form (assuming a WinForms example here)
' Declare these two globally
Dim readLines() As String
Dim count As Integer = 0
Private void Form_Load(sender As Oject, e As EventArgs) Handles Base.Load
' In form load, read the file, just one time
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
readLines() As String = IO.File.ReadAllLines(myFile)
else
TextBox1.Text "File not found"
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Check if you have a file and if you don't have reached the last line
if readLines IsNot Nothing AndAlso count < readLines.Length Then
TextBox1.Text = readLines(count)
count += 1
else
TextBox1.Text "End of file"
End If
End Sub
This reduces the amount of code you need to write:
TextBox1.Text = readLines(count - 1)