-3

I am trying to create a Desktop Application that is basically a pet orphanage for people to donate and receive pets without home. I created my database and my design for the app, but my progress is blocked by the fact that whatever variables, parameters or anything I create inside the public : Form2 ( ) constructor cannot be used inside the rest of the code. I have multiple tutorials that I follow for the moment in order to create my application, and all of the use the same approach ( Create database connection inside the constructor of the form, where InitializeComponents() is located, then use that same connection throughout the code ).

I seem to encounter an issue that basically stops me from using anything created inside the constructor ( image below ). enter image description here

This is stopping me not only with the connection. For example if I create an instance of an User Control like this:

ucHome home1 = new ucHome(); home1.BringToFront();

Everything is working fine and the UC is brought to front but if somewhere in the code ( anywhere ) like a Button-Click function I try to use the method home1.SendToBack() for example the code will not recognize home1 and will tell me it is undeclared.

Any ideas of how I might fix this?

Thank you!

  • 2
    First of all, please don't post pictures of code, post the actual text here. Secondly, you have defined the variable `databaseConnection` inside the constructor so that is where is is scoped to. – DavidG Aug 31 '22 at 12:28
  • [What is the difference between a member variable and a local variable?](https://stackoverflow.com/q/1177723) – 001 Aug 31 '22 at 12:29
  • Don't cache conection objects. Just create them when you need them, and dispose iwth `using`. See [C# Data Connections Best Practice?](https://stackoverflow.com/questions/17552829/c-sharp-data-connections-best-practice) – Charlieface Aug 31 '22 at 12:35

1 Answers1

0

You can pass the sql context at GetData method because actually your context scope is only the constructor.

Try this

private void GetData(MySQLConnection sqlConnection)
{
// Data find
}

Do not forget call GetData method on form2 constructor.

Mehdi Kacim
  • 131
  • 5