Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

Use a variable from another method in C#

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...