0

I'm working in C# and having trouble passing a variable back to a function thats inside a button click.

So I have a form with a button on it.

private void button3_Click(object sender, EventArgs e)
{
    int count = 0;
    new EvaluateQuery().RunQuery(_Query,count);

I have a count variable initialized to 0. It passes this value to another function. It serves as the index for an array in my EvaluateQuery function.

Basically, the function does some magic and stops. Once the magic is done, I increment my count variable. The incremented value should be then passed back to my EvaluateQuery function, so if the button is clicked again, it can pass a value of 1 to my function and so on and so on. I'm having trouble passing the incremented value back though.

I am really at a standstill on this. Any help on this topic would be greatly appreciated. Thanks in advance.

2
  • 1
    You have to pass the count by ref. Check this article: msdn.microsoft.com/en-ca/library/14akc2c7.aspx for more details. Why can't you make the function return the count instead? Commented Sep 26, 2014 at 16:04
  • 2
    on button click alway your count will come to 0 again Commented Sep 26, 2014 at 16:04

1 Answer 1

3

If count is intended to be modified by RunQuery then it needs to be passed by ref. Alternatively, that function could return the count, and you could just assign it.

Either way, you have the larger problem of count having function scope. This means that the variable is lost when the function exits, and recreated when it is called again (in this case, each time the user clicks the button).

count should be in the class scope to fix this issue, as its lifetime will be that of the form.

Sign up to request clarification or add additional context in comments.

Comments

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.