parman
parman

Reputation: 127

How to Access a Variable in Multiple Methods

I have function openport, which opens a serial port. But when I need to use the serial port in other functions, I get an error that the name does not exist in the current context. I tried to change private to public, but it's still not working. For example:

public void openportbtn_Click(object sender, EventArgs e)
{
    SerialPort seriovyport = new SerialPort(COMtb.Text);
    seriovyport.Open();
    //here I crate serial port with COM from text box and open it

}

//but if i want to use it anywhere else
public void closeportbtn_Click(object sender, EventArgs e)
{
    seriovyport.Close(); //I get error
}

How can I make the serial port public?

(sorry for my English | my first post on this forum)

Upvotes: 4

Views: 956

Answers (1)

itsme86
itsme86

Reputation: 19486

You can create a class-level field to reference the port instead:

private SerialPort seriovyport;

public void openportbtn_Click(object sender, EventArgs e)
{
    seriovyport = new SerialPort(COMtb.Text);
    seriovyport.Open();
}

public void closeportbtn_Click(object sender, EventArgs e)
{
    seriovyport.Close();
}

Upvotes: 6

Related Questions