简体   繁体   中英

C# Passing values to another form

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
       }
    }

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
   }
}
public Form2(DataGridView dgv, bool _useDBServer, bool useOther)
    {
       useDBServer = _useDBServer;

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

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
   }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM