tags:

views:

486

answers:

4

Hi all,

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
       }
    }
+5  A: 

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
   }
}
Jon Skeet
Thanks Jon, I've learnt something new.
Jamie
A: 
public Form2(DataGridView dgv, bool _useDBServer, bool useOther)
    {
       useDBServer = _useDBServer;

       if(useDBServer) //<---- works here
       {
         //stuff
       }
    }
Preet Sangha
A: 

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
   }
}
Matt Lacey
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 Lacey
@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
Why is this downvoted?
Josh Smeaton
Matt Lacey
A: 

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.

Josh Smeaton