Reputation: 23
I know this has been asked before but I still can't figure it out and those answers don't help. I need to know how to do exactly what the code below shows but successfully.
public void ProgressBar_MouseDown(object sender, EventArgs e)
{
int somevariable;
}
public void ProgressBar_MouseUp(object sender, EventArgs e)
{
int anothervariable = somevariable;
}
Upvotes: 1
Views: 87
Reputation: 506
So you have 2 different events that are called from 2 different actions. So the basic answer would be you can't pass a value from one action to another directly. For doing this you would need to declare that "_somevariable" as a global variable, but in C# we don't have that so the next best solution would be to use static class and static variables.
Action 1: Mouse Down call's ProgressBar_MouseDown
Action 2: Mouse UP call's ProgressBar_MouseUp
public static class GlobalVariables
{
public static int somevariable { get; set; }
}
public void ProgressBar_MouseDown(object sender, EventArgs e)
{
//changing _somevarible
//somevarible=set your value here
}
public void ProgressBar_MouseUp(object sender, EventArgs e)
{
//int anothervariable = somevariable;
//here you should be able to access the somevariable
}
Upvotes: 0
Reputation: 156
Take your method,
public void ProgressBar_MouseDown(object sender, EventArgs e)
{
int somevariable;
}
Imagine the method as a black box with an input and an output - you can put data in and receive data out, but you don't know what's happening on the inside of the box.
Therefore, when you create int someVariable
inside the method, nothing else in your code can 'see' this.
To get around this issue, you should use variables inside your class, like so:
public class Program
{
private int somevariable;
public void ProgressBar_MouseDown(object sender, EventArgs e)
{
// Operate on somevariable
}
public void ProgressBar_MouseUp(object sender, EventArgs e)
{
int anothervariable = somevariable;
}
}
If we go back to the black box analogy, now imagine that it has a peephole that it can only look out of. Therefore, your methods (black box) can look out into the class and 'see' the int somevariable
, but other objects still cannot look inside the method.
You could also pass somevariable
between methods, however by the looks of it you are responding to UI events, and therefore can't do this easily.
Upvotes: 1
Reputation: 311
private int _somevariable;
public void ProgressBar_MouseDown(object sender, EventArgs e)
{
//changing _somevarible
}
public void ProgressBar_MouseUp(object sender, EventArgs e)
{
int anothervariable = _somevariable;
}
Local varibles exists only during method execution.
Upvotes: 3