Reputation: 155
Can a button return the value of a variable?is it possible? I'm new in winform so...understand me. The final goal is to have a simple code with two buttons that if clicked return a msgbox with the value of a var.
private string button3_Click(object sender, EventArgs e)
{
string res = "PASS";
MessageBox.Show(res);
return res;
}
private string button4_Click(object sender, EventArgs e)
{
string res = "FAIL";
MessageBox.Show(res);
return res;
}
Upvotes: 1
Views: 1805
Reputation: 37337
Click event handlers have strongly typed signature, i.e. the return type must be void
, so you cannot return anything from them.
But, if you are working with windows Forms, you have class for your form, where you placed those event hadnlers. So what you can do is: define private variable:
pirvate string _res;
and then assign it value in your click event hadlers, eg.:
private string button3_Click(object sender, EventArgs e)
{
_res = "PASS";
MessageBox.Show(_res);
}
Then in the code you could use this value as you want.
If you want to use it outside your class, define property:
public string Res
{
get { return _res; }
}
Upvotes: 0
Reputation: 186668
Well, button3_Click
and alike are so-called callback functions which are called by system and that's why do not return any value (the system doesn't need it). Let's extract a method:
private string MyButtonClick(object sender) {
string result = "";
if (sender == button3)
result = "PASS"; //TODO: better read it from resources, not hadcoded
else if (sender == button4)
result = "FAIL"; //TODO: better read it from resources, not hadcoded
if (!string.IsNullOrEmpty(result))
MessageBox.Show(result);
return result;
}
And then you can put:
// System callback function
// void: System callback function signature
private void button3_Click(object sender, EventArgs e) {
MyButtonClick(sender);
}
// void: System callback function signature
private void button4_Click(object sender, EventArgs e) {
MyButtonClick(sender);
}
Or
// custom code
string myClickMessage = MyButtonClick(button4);
Upvotes: 1