Home>

On a C # form application
I want to assign the character entered in the text to a variable and use it for other processing.
I'm sorry for beginners and stubborn content. Thank you.

Applicable source code

C #
namespace WindowsFormsApp2
{
public partial class Form1: Form
{
public Form1 ()
{
InitializeComponent ();
}

private void OnTagsReported (ImpinjReader sender, TagReport report) // Move when information is acquired from the sensor
{
if (moji == "0001") // I want to use moji's variable obtained with Button1_Click as it is.
{
// Process
}
}
private void Button1_Click (object sender, EventArgs e)
{
string moji = textBox1.Text;
}
}
}
`` `

  • Answer # 1

    By defining

    class member variables asstring _moji, member variables can be used for methods in the same class.

    namespace WindowsFormsApp2
    {
        public partial class Form1: Form
        {
            // By defining at class scope
            // Create a member variable that can be accessed by any method
            private string _moji = null;
            public Form1 ()
            {
                InitializeComponent ();
            }
            private void OnTagsReported (ImpinjReader sender, TagReport report) // Move when information is acquired from the sensor
            {
                if (_moji == "0001") // I want to use the moji variable obtained with Button1_Click as it is.
                {
                    //processing
                }
            }
            private void Button1_Click (object sender, EventArgs e)
            {
                // This is an assignment to a local variable
                // moji cannot be used across methods
                // string moji = textBox1.Text;
                // By assigning to member variable _moji
                // Make it accessible from another method
                _moji = textBox1.Text;
            }
        }
    }

  • Answer # 2

    Themojideclared in theButton1_Clickmethod is a local variable and a variable local to the method. Therefore, it cannot be taken out of the method.
    In order to notify the outside, input is received from the outside by reference or notified as a return value.
    But since it's a button click event handler, the signature cannot be changed.
    Therefore, it can be referenced in the class as a class variable.

    Please click "" to enter the source code in the `` `entered.

  • Answer # 3

    Roughly speaking, the accessible range of a variable depends on where it is declared.
    Learn about variable scope.