Search code examples
c#functionbuttoncallreusability

c# use a local variable in another button


I'm currently playing with the Ftp.dll library from https://www.limilabs.com/ftp and I'm having a problem implementing a Disconnect button.

When I type client.Close(); in FTPDisconnectbtn_Click I'm getting the error:

The name 'client' does not exist in the current context.

If I understand correctly it's because the client is not specified (I don't know the exact term) in the Disconnect button, but only on the Connect one.

What I want is to be able to reuse the client from the FTPConnectbtn_Click function in any other buttons.

How does one do this correctly?

Thanks a lot for helping me!!!

my current code:

        private void FTPConnectbtn_Click(object sender, EventArgs e)
    {
        using (Ftp client = new Ftp())
        {
            if (FTPSSLcheck.Checked)
            {
                client.ConnectSSL(FTPhosttext.Text);
            }
            else
            {
                client.Connect(FTPhosttext.Text);
            }
            client.Login(FTPusertext.Text, FTPpasstext.Text);
            Limilabs.FTP.Log.Enabled = true;
            Limilabs.FTP.Log.WriteLine += Console.WriteLine;

            client.ChangeFolder("pub");

            List<FtpItem> items = client.GetList();

            foreach (FtpItem item in items)
            {
                FTPlistBox1.DataSource = items;
            }
        }
    }


    private void FTPDisconnectbtn_Click(object sender, EventArgs e)
    {
     client.Close();
    }

Solution

  • This is nothing to do with the package, but is a basic C# question (the word "basic" was not intended to be insulting, more meaning that it's something fundamental you need to understand).

    The client variable is declared inside a using statement in the FTPConnectbtn_Click method. That means it's a local variable, only available within the block (curly braces) for that using. If you were to try to access it in the rest of the method you'd get the same error.

    What you need to do is declare a class-level variable for client, and store the connection in that, so it's available in other methods. This means that you lose the benefit of the using statement closing the connection for you, so you'll have to close it manually when you're done.

    Search around for "C# variable scope" for more info on this. It's a very important issue that you'll need to understand for all your coding.

    Hope that helps.