When working with C#, accessing variables defined in one method from another can be a common challenge, especially for beginners. Let's explore a possible solution to this issue.
Problem:
You have created a form in C# with a text box named "readG" and another named "readQ". You want to read the numbers entered into these text boxes using individual methods ("readG_TextChanged" and "readQ_TextChanged") and then perform an operation with the obtained decimal values in a third method ("button1_Click"). However, the decimal values obtained in the first two methods (_Gd and _Qd) are not accessible within the third method.
Answer:
To resolve this issue, you can declare the _Gd and _Qd variables at the class level instead of within the individual methods. By doing so, these variables will be accessible throughout the class, including within the "button1_Click" method.
Here is an adjusted version of your code:
private decimal _Gd; private decimal _Qd; public void readG_TextChanged(object sender, EventArgs e) { string _G = readG.Text; _Gd = Convert.ToDecimal(_G); } public void readQ_TextChanged(object sender, EventArgs e) { string _Q = readQ.Text; _Qd = Convert.ToDecimal(_Q); } private void button1_Click(object sender, EventArgs e) { decimal _ULS = (1.35m * _Gd + 1.5m * _Qd); Console.WriteLine("{0}",_ULS); }
By declaring _Gd and _Qd at the class level, you ensure that they are available for use in the "button1_Click" method, allowing you to successfully perform the desired operation.
The above is the detailed content of How Can I Access Variables from Different Methods in a C# Form?. For more information, please follow other related articles on the PHP Chinese website!