1

I have 2 buttons, Connect and Send Command. In the first button I am creating the connection to my server and in the second sending a command. The codes are as below:

public void button1_Click(object sender, EventArgs e)
{
      SshExec shell = new SshExec("hostname", "username", "password");
      shell.Connect();
}

public void button2_Click(object sender, EventArgs e)
{
      shell.RunCommand("ls");
}

Now the error is in "shell.RunCommand("ls");" I am getting "The name 'shell' does not contains in the current context". I am new to C# (mere 2 days) and do not have much idea, so please if anyone can help. What I am expecting is no error and the command to be sent properly to the terminal when the second button is pressed. At the end sorry for bad formatting of the code, please inform me if any additional information is required.

M.S.
  • 4,283
  • 1
  • 19
  • 42
  • Your variable `shell` is local to the first method. It doesn't exist outside it. Move the declaration to the class level. – Sami Kuhmonen Apr 02 '16 at 16:02
  • Thanks Sami for the suggestion but due to some other constraints I cannot move it to the class. Is there any other way by which I can make this variable accessible to all ?? – Satyajeet Mishra Apr 02 '16 at 16:53
  • 1
    Do explain what these constraints are. Because that is the proper way to do it. Of course you can play with singletons, but that is very poor design. – Sami Kuhmonen Apr 02 '16 at 16:56

1 Answers1

0

Right now, you are declaring the variable shell inside the button1_Click method. That means only that method can "see" the variable and use it.

In order for both of the button methods to use the variable, it must be declared outside/above at the class level.

Try this:

private SshExec shell;

public void button1_Click(object sender, EventArgs e)
{
      shell = new SshExec("hostname", "username", "password");
      shell.Connect();
}

public void button2_Click(object sender, EventArgs e)
{
      shell.RunCommand("ls");
}
Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147