VB.net add line break after each loop - vb.net

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

Related

How to only accept certain values inside a textbox

I made a flashcard application where the user can change the difficulty by entering a number inside a textbox.
Sub UpdateDifficultyLevel(front As String, difficulty As Integer)
'The parameters are represented by question marks in the query
Dim sql = "UPDATE flashcards SET difficulty = ?
WHERE Front = ?"
'This using statement The Using statement makes sure that any "unmanaged resources" are released after they've been used.
Using conn As New OleDbConnection("provider=microsoft.ACE.OLEDB.12.0;Data Source=flashcard login.accdb"), 'Establish connection
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add("#difficulty", OleDbType.Integer).Value = difficulty 'Updates database with parameters
cmd.Parameters.Add("#front", OleDbType.VarWChar).Value = front 'Updates database with parameters
conn.Open() 'Opens connection
cmd.ExecuteNonQuery() 'Executes
End Using
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim difficulty As Integer 'Sets difficulty as integer
If Integer.TryParse(TxtDifficulty.Text, difficulty) Then
Dim front = txtFront.Text 'Defines front as variable which is equal to txtfront.text
UpdateDifficultyLevel(front, difficulty) 'Calls subroutine
Else
MsgBox("Please enter a number between 1 and 3") ' tells user that the difficulty must be a number
End If
End Sub
This works where the user can only enter an integer but how would I make it so they can only enter an integer between 1 and 3
You can utilize ErrorProvider to feedback to the user that the input is wrong. And reuse the validate function to get the parsed integer when used (so the logic is only in one place)
Private errorMessage As String = "Please enter a number between 1 and 3"
Private Function validateInput(ByRef difficulty As Integer) As Boolean
Return Integer.TryParse(TxtDifficulty.Text, difficulty) AndAlso difficulty >= 1 AndAlso difficulty <= 3
End Function
Private Sub TxtDifficulty_TextChanged(sender As Object, e As EventArgs) Handles TxtDifficulty.TextChanged
If Not validateInput(Nothing) Then
ErrorProvider1.SetError(TxtDifficulty, errorMessage)
TxtDifficulty.SelectAll()
Else
ErrorProvider1.SetError(TxtDifficulty, "")
End If
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim difficulty As Integer 'Sets difficulty as integer
If validateInput(difficulty) Then
Dim front = txtFront.Text 'Defines front as variable which is equal to txtfront.text
UpdateDifficultyLevel(front, difficulty) 'Calls subroutine
Else
MsgBox(errorMessage) ' tells user that the difficulty must be a number
End If
End Sub
There are many other, possibly better, ways to do this however, but this sticks with your current design.
Use a NumericUpDown control instead, with its Increment set to 1, MinValue set to 1 and MaxValue set to 3. It looks just like a textbox and, bonus, you can change the number within using the arrow keys
You can also consider a MaskedTextBox, RadioButtons, ComboBox, ListBox, even 3 different buttons to start an Easy, Medium or Hard game..
A big part of effective UI design is in using tools designed for purpose and not bothering the user with an endless succession of error messages that they have to read, understand and apply corrections for. A great example of that gone wrong is a cellphone with a Symbian OS; they were renown for bothering the user with incessant messages.
If you have an opportunity to design a UI so the user simply can't get it wrong, rather than shouting at them when they do, take it; your iPhone doesn't present a Qwerty keyboard when you're dialling a number..

How am I able to loop my random number generator in VB.net

vb.net noob here, I've been trying to make it so everytime i click "button2" it will generate a new number on a label, and that works perfectly but I cannot seem to make it generate a new number everytime the button is pressed I usually have to restart the program for a different number.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles generateButton.Click
While resultString.Length < 40
If overGen.Next(0, 2) = 0 Then
resultString &= letterGen(overGen.Next(0, letterGen.Length))
Else
resultString &= symnumGen(overGen.Next(0, symnumGen.Length))
End If
End While
Label1.Text = resultString
End Sub
Because that resultString apparently has class-scope it keeps its value and on the next click the length is still 40. So nothing new is generated.
Solution:
Make that resultString local to your click handler (best option if you don't need that value elsewhere).
Or set it to an empty string at the start of that handler, so you really create a new value.

How do I validate user input?

So I'm having a problem with my code. I need to validate if the user input is a number or not in a textbox. Now I can get it to see whether or not it is a number and it displays the error message just fine but the problem is that the word still gets inputted in to the textbox when I want there to be only numbers
If tried using if not IsNumeric(Number) then
msgbox.show("ERROR! Data must be a number!")
'Getting user input
Dim Number As String = Me.InputTextbox.Text
UnitsTextbox.AppendText(Environment.NewLine & Number)
'Make the textbox delete the text once the button is clicked
InputTextbox.Text = String.Empty
If Not IsNumeric(Number) Then
MsgBox("ERROR! Data must be a number")
End If
I'm expecting it to accept numbers only
i have a text box for input and a textbox for the results and when the number comes up false I want it to not show in the results textbox
As per #Jens comments, only I changed it to .TryParse. IsNumeric is an old VB6 method that has been optimized in .Net to TryParse.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim output As Integer
If Not Integer.TryParse(InputTextbox.Text, output) Then
MessageBox.Show("ERROR! Data must be a number")
Else
UnitsTextbox.AppendText(Environment.NewLine & InputTextbox.Text)
InputTextbox.Text = String.Empty
End If
End Sub

How do I send a Skype message to multiple contacts in a list from a textbox?

I would like to know how to send a Skype message to multiple contacts at a time. For example, the textbox contains this:
user1
user2
user3
Right now, to send a message to a specific contact I use:
Skypattach.SendMessage("username", "message")
So instead of having to do
Skypattach.SendMessage("username1", "message")
Skypattach.SendMessage("username2", "message")
Skypattach.SendMessage("username3", "message")
I would like it to be quicker, to grab the usernames from a textbox.
Thanks for your time.
To flesh out my comment, the TextBox control has a Lines Property which you can iterate through to get each individual line. So if your text looks exactly like what your question shows, you can use something like this. Notice that I am splitting on the period, you can use the space or what ever delineator you decide on.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SendSkype(TextBox1.Lines)
End Sub
Private Sub SendSkype(rawUserNameData As String())
Dim x As Integer
Dim receipients() As String
If rawUserNameData.Count > 0 Then
ReDim receipients(rawUserNameData.Count - 1)
For x = 0 To rawUserNameData.Count - 1
Try
receipients(x) = Trim(Split(rawUserNameData(x), ".")(1))
Catch ex As IndexOutOfRangeException 'Catch Unproperly formatted entries
End Try
Next
For Each s As String In receipients
Skypattach.SendMessage(s, "Message")
Next
End If
End Sub

VB 2013 Comparisons between user input and application memory

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