0

I'm trying to start a cmd console and run a command. The command has two points where I need to have user input which is why I have made the string "cmdcode" where it combines preset info and the user input. When the program is ran I get the error code "Object reference not set to an instance of an object." two times, once referring to the whole line where cmdcode is created and once referring to the actual variable "cmdcode" on that same line. What is happening and if there is a different way to do it then how.

Also if anyone knows how to run the "process.start()" command "x" number of times that would be great.

Public Class Form1
    Dim cmdcode As String = "ping" + TextBox1.Text + "-t -l" + TextBox2.Text
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    End Sub
    Private Sub STARTBUTTON_Click(sender As Object, e As EventArgs) Handles STARTBUTTON.Click
        Process.Start("CMD", cmdcode)
    End Sub
End Class
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Deemo
  • 131
  • 1
  • 1
  • 10
  • 1
    Specifically, the section "Visual Basic Forms" in this answer : http://stackoverflow.com/a/26761773/327083 -- `TextBox1` and `TextBox2` will not yet be created when the field `cmdcode` is initialized. Form fields are initialized before the call to `InitializeComponent` which creates your components. – J... Dec 09 '15 at 23:46
  • Also... http://stackoverflow.com/search?q=Object+reference+not+set+to+an+instance+of+an+object. ;) – J... Dec 09 '15 at 23:48

1 Answers1

0

You can't access controls before they are initilized.

Here:

Dim cmdcode As String = "ping" + TextBox1.Text + "-t -l" + TextBox2.Text

Is trying to access them and this is before they have been initialized. Those textboxes also don't have any input at that time, maybe a button to send that command.

Do something like:

Public Class Form1

  Dim cmdcode As String 

  Private Sub btnStart(sender As Object, e As EventArgs) Handles btnStart.Click
     cmdcode = "ping" + TextBox1.Text + "-t -l" + TextBox2.Text
     Process.Start("CMD", cmdcode)
  End Sub
OneFineDay
  • 9,004
  • 3
  • 26
  • 37