C# my string is in block of code, can read the string outside of the block of code

Advertisements

I have a string name called mydata in a public void. Like so:

        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            string mydata = ((SerialPort)sender).ReadExisting();
        }

after this code I have a button code with an if statment. Like so:

        private void button1_Click(object sender, EventArgs e)
        {
            if (mydata == "Random")
            {
                //DO Function
            }
        }

The if statement which includes mydata gives an error "The name mydata does not exist inthe current context.

My question is can I change the private void to public and then i can pull the data from mydata string? How is this done!

I have tried changing private to public thinking i can retrieve mydata string but that did not work.

>Solution :

Access modifiers (private, et al) aren’t really the issue here. It’s a matter of variable scope. Generally when a method needs to "send a value" or "receive a value" to/from another method, we’d be talking about method arguments and return values.

However, what you have are event handlers, which don’t directly call one another. So passing values and returning values aren’t really an option.

The data would need to be stored in a common location both can see. For example, if both of these are in the same class, and if the same instance of that class is being used here, then you can store the value in a class-level field. For example:

private string mydata;

private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    mydata = ((SerialPort)sender).ReadExisting();
}

private void button1_Click(object sender, EventArgs e)
{
    if (mydata == "Random")
    {
        //DO Function
    }
}

Note that if different instances of the class need to share this data (a common example that trips up beginners is ASP.NET pages on different requests) then you’d need to raise the scope of the value even more, persisting it to some storage outside of the class itself. A database, for example.

Leave a ReplyCancel reply