0

I'm passing a bool from one form to another, I have tried declaring 'Private bool useDBServer;' at the top of my class but this create a new variable.

What am I doing wrong?

Thanks

Form1 below:

Form2 frm = new Form2(dataGridView1, _useDBServer, _useOther);

Form2 below:

    public Form2(DataGridView dgv, bool useDBServer, bool useOther)
    {
       if(useDBServer) //<---- works here
       {
         //stuff
       }
    }


    private void readRegistry()
    {
       if(useDBServer) //<---- but not here
       {
         //stuff
       }
    }

4 Answers 4

5

If you want to use the variable in a different method, you'll have to have it as an instance variable, and copy the value in the constructor:

private readonly bool useDBServer;

public Form2(DataGridView dgv, bool useDBServer, bool useOther)
{
   this.useDBServer = useDBServer; // Copy parameter to instance variable
   if(useDBServer) 
   {
     //stuff
   }
}


private void readRegistry()
{
   if(useDBServer) // Use the instance variable
   {
     //stuff
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0
public Form2(DataGridView dgv, bool _useDBServer, bool useOther)
    {
       useDBServer = _useDBServer;

       if(useDBServer) //<---- works here
       {
         //stuff
       }
    }

Comments

0

Do something like this:

bool localUseDBServer;

public Form2(DataGridView dgv, bool useDBServer, bool useOther)
{
   localUseDBServer = useDBServer;

   if(localUseDBServer)
   {
     //stuff
   }
}

private void readRegistry()
{
   if(localUseDBServer)
   {
     //stuff
   }
}

3 Comments

is the down vote just because I posted the same thing as 2 other people at the same time? Or is there something wrong in what I posted?
@Matt: I didn't downvote, but I wouldn't call an instance variable "localXXX"... it sounds like it's meant to be a local variable.
@Jon Skeet - Didn't mean to imply you down voted. Someone did & I wondered why. Yes the name is bad but I wanted to imply the variable was local to the class without putting in the code to show this.
0

You're passing an argument to the constructor. How is that going to be used in a method within the class? You either need to 'save' the argument in an instance member variable. Or you need to forward the argument from the constructor to the method.

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.