Rikus Honey
Rikus Honey

Reputation: 558

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.

Upvotes: 0

Views: 932

Answers (1)

Tasos K.
Tasos K.

Reputation: 8079

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

Upvotes: 4

Related Questions