0

I am new to C# programming and am very inexperienced.

I'm creating a form with a text box, and I want my program to read numbers in that box in a method, and execute an operation with those numbers in another method. Here's how it is by now:

public void readG_TextChanged(object sender, EventArgs e)
{
    string _G = readG.Text;
    decimal _Gd = Convert.ToDecimal(_G);
}

public void readQ_TextChanged(object sender, EventArgs e)
{
    string _Q = readQ.Text;
    decimal _Qd = Convert.ToDecimal(_Q);
}
private void button1_Click(object sender, EventArgs e)
{
    decimal _ULS = (1.35m * _Gd + 1.5m * _Qd);
    Console.WriteLine("{0}", _ULS);
}

readQ, readG are the boxes names. button1 is the button to proceed to the operation, and display it in a console.

So far I have the _Gd and _Qd out of context in the button1_click method. Besides that, I think it will run pretty fine.

1
  • Why do the variable names start with an underscore? Commented Jan 17, 2021 at 5:46

2 Answers 2

3

You should read up on scoping... http://msdn.microsoft.com/en-us/library/ms973875.aspx

One way is for your _Qd and _Gd to be at the class level, not defined within the methods themselves, so that you have access to them in the click method.

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

This concerns variable scope. The variables _Qd and _Gd only have scope within their methods.

You could make them class members, that is declare them outside your methods, in the main body of the class, as follows:

 private decimal _Gd;
 private decimal _Qd;

.

Then you can set them like this:

 _Gd = Convert.ToDecimal(_G);
 _Qd = Convert.ToDecimal(_Q);

These variables will be visible from within any method in your class.

1 Comment

yes i'm aware of scoping, i know that is exactly the problem i understood and used your solutions and worked perfecty.. i had to change console. commands to messagebox instead thank you all very much for the quick and effective answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.