How to make a variable accessible to the whole application?

A

adodotnet20

I'm developing a Windows application and I'm having some problems in
making variable accessible to the whole application. I use VS.NET 2005
and I create a database connection object in the method private void
connect_Click(object sender, EventArgs e). That object I create seems
to be accessible only within that method, how do I make it accessible
to the whole application, just like I have access to mytextbox.text
throughout my tabbed form? Where do you keep your connection object
usually?

Thank you.
 
G

Guest

C# does not support global variables. You can declare variables outside of
functions. These are called member variables.

class Fake
{
public int MyInt;
}

Anything accessing Fake.MyInt can read it. If you have a function in the
class, it can also read MyInt.
 
B

Ben Voigt

I'm developing a Windows application and I'm having some problems in
making variable accessible to the whole application. I use VS.NET 2005
and I create a database connection object in the method private void
connect_Click(object sender, EventArgs e). That object I create seems
to be accessible only within that method, how do I make it accessible
to the whole application, just like I have access to mytextbox.text
throughout my tabbed form? Where do you keep your connection object
usually?

You would do that with a class member variable.

You are not ready for database access if you are unfamiliar with basic
programming concepts such as scope. I suggest that you complete a tutorial
that teaches structured programming and object-oriented programming in C#
before continuing work on your application.
 
C

C# Beginner

I'm one of those guys who don't like public variables. My solution is this:
Create a database class in which you store database members such as
connectionstring property/variable, Open() methods etc. In the starting form
I create an instance of this database class. When another form needs access
to the database, I parse the instance using the tag property tag of the
form.

NewForm.Tag = (object) myDatabase;

Within the new form you can use
.... = (Database) this.tag.

hope you can use it

DD
 
G

Guest

Just add a separate class file to your application and add in all the
required fields as public with the "static" modifier.
Then you can refer to these from anywhere with "MyStuff.FieldName".
Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top