Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Accessing Data stored in a class

Accessing Data stored in a class

Scheduled Pinned Locked Moved C#
databasequestionannouncement
10 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    Gavin_Mannion
    wrote on last edited by
    #1

    Hi All, I have a class called Database.cs which is called when my application is started up. This class then populates 2 arrays with data from my SQL database. --Update-- I have also just noticed that once I move to another part of my application these arrays seem to vanish? am I going about this all the wrong way? --Update-- Now I am trying to access these arrays and am running into problems. I have the following code so far. =============== Database sn = Database(); int j = sn.StaffNames.getUpperBound; =============== Which doesn't work and if I change the first line to Database sn = new Database(); I think it is clearing my arrays? Thanks, :eek: :eek: :eek: :eek:

    J 1 Reply Last reply
    0
    • G Gavin_Mannion

      Hi All, I have a class called Database.cs which is called when my application is started up. This class then populates 2 arrays with data from my SQL database. --Update-- I have also just noticed that once I move to another part of my application these arrays seem to vanish? am I going about this all the wrong way? --Update-- Now I am trying to access these arrays and am running into problems. I have the following code so far. =============== Database sn = Database(); int j = sn.StaffNames.getUpperBound; =============== Which doesn't work and if I change the first line to Database sn = new Database(); I think it is clearing my arrays? Thanks, :eek: :eek: :eek: :eek:

      J Offline
      J Offline
      James T Johnson
      wrote on last edited by
      #2

      Gavin_Mannion wrote: int j = sn.StaffNames.getUpperBound; Assuming StaffNames is the array; the name should be GetUpperBound (uppercase G), and it is a function that takes an integer specifying which dimension you want the upper bound from. int j = sn.StaffNames.GetUpperBound(0); That should give you the value you wanted, and yes the first line should be Database sn = new Database() assuming you are meaning to create a new instance of your Database class. The only thing that could cause your arrays to be cleared is by either calling Clear() on the array, or by assigning a new array to it. I have a feeling that it only seems that your arrays are being cleared though, so try the first fix and if that doesn't work reply back and I'll look into it further. More code would help as well, at least a generalized version of your code :) James Sonork ID: 100.11138 - Hasaki "My words but a whisper -- your deafness a SHOUT. I may make you feel but I can't make you think." - Thick as a Brick, Jethro Tull 1972

      G 1 Reply Last reply
      0
      • J James T Johnson

        Gavin_Mannion wrote: int j = sn.StaffNames.getUpperBound; Assuming StaffNames is the array; the name should be GetUpperBound (uppercase G), and it is a function that takes an integer specifying which dimension you want the upper bound from. int j = sn.StaffNames.GetUpperBound(0); That should give you the value you wanted, and yes the first line should be Database sn = new Database() assuming you are meaning to create a new instance of your Database class. The only thing that could cause your arrays to be cleared is by either calling Clear() on the array, or by assigning a new array to it. I have a feeling that it only seems that your arrays are being cleared though, so try the first fix and if that doesn't work reply back and I'll look into it further. More code would help as well, at least a generalized version of your code :) James Sonork ID: 100.11138 - Hasaki "My words but a whisper -- your deafness a SHOUT. I may make you feel but I can't make you think." - Thick as a Brick, Jethro Tull 1972

        G Offline
        G Offline
        Gavin_Mannion
        wrote on last edited by
        #3

        Okay the error message I get is the following ------------------ An unhandled exception of type 'System.NullReferenceException' occurred in LTBRMaintenance.exe Additional information: Value null was found where an instance of an object was required ------------------ My code looks like this =============== Database sn = new Database(); //Database is the name of my class int h = sn.StaffNames.GetUpperBound(0); //StaffNames Array Name =============== My Database.cs code looks like this =============== public class Database { public string[] StaffNames; public Database() { } public void LoadStaff() { SqlConnection myConnection; myConnection = new SqlConnection("server=127.0.0.1; uid=;pwd=;database=LondonTBR"); string sql = "ltbr_GetStaff 0"; // Connect to the SQL database using a "Stored Procedure" SqlCommand myCommand; myCommand = new SqlCommand(sql, myConnection); myConnection.Open(); SqlDataReader dReader; dReader = myCommand.ExecuteReader(); int j = 0; int ArrayCount = 0; //Set Array to correct size if (dReader.Read()) { ArrayCount = dReader.GetInt32(0); StaffNames = new string[ArrayCount]; } dReader.NextResult(); //Populate Array while (dReader.Read()) { StaffNames[j] = dReader.GetString(2) + ", " + dReader.GetString(1); j = j + 1; } dReader.Close(); myConnection.Close(); myCommand.Dispose(); } } } =============== If I step through the code the function LoadStaff() is called and does execute without any problems. Let me know if you spot something I am doing wrong here :) Thanks,

        J 1 Reply Last reply
        0
        • G Gavin_Mannion

          Okay the error message I get is the following ------------------ An unhandled exception of type 'System.NullReferenceException' occurred in LTBRMaintenance.exe Additional information: Value null was found where an instance of an object was required ------------------ My code looks like this =============== Database sn = new Database(); //Database is the name of my class int h = sn.StaffNames.GetUpperBound(0); //StaffNames Array Name =============== My Database.cs code looks like this =============== public class Database { public string[] StaffNames; public Database() { } public void LoadStaff() { SqlConnection myConnection; myConnection = new SqlConnection("server=127.0.0.1; uid=;pwd=;database=LondonTBR"); string sql = "ltbr_GetStaff 0"; // Connect to the SQL database using a "Stored Procedure" SqlCommand myCommand; myCommand = new SqlCommand(sql, myConnection); myConnection.Open(); SqlDataReader dReader; dReader = myCommand.ExecuteReader(); int j = 0; int ArrayCount = 0; //Set Array to correct size if (dReader.Read()) { ArrayCount = dReader.GetInt32(0); StaffNames = new string[ArrayCount]; } dReader.NextResult(); //Populate Array while (dReader.Read()) { StaffNames[j] = dReader.GetString(2) + ", " + dReader.GetString(1); j = j + 1; } dReader.Close(); myConnection.Close(); myCommand.Dispose(); } } } =============== If I step through the code the function LoadStaff() is called and does execute without any problems. Let me know if you spot something I am doing wrong here :) Thanks,

          J Offline
          J Offline
          James T Johnson
          wrote on last edited by
          #4

          When is the LoadStaff() function called? In the first code block you create the Database object then immediately try to read the StaffNames without calling the Load. If you will always be calling LoadStaff when you create a Database object you should place a call to LoadStaff() in the constructor for the Database class. If you won't be calling LoadStaff everytime then you should create a new StaffNames array.

          public Database() {
          LoadStaff();
          }

          or

          public Database() {
          StaffNames = new string[0]
          }

          HTH, James Sonork ID: 100.11138 - Hasaki "My words but a whisper -- your deafness a SHOUT. I may make you feel but I can't make you think." - Thick as a Brick, Jethro Tull 1972

          G 1 Reply Last reply
          0
          • J James T Johnson

            When is the LoadStaff() function called? In the first code block you create the Database object then immediately try to read the StaffNames without calling the Load. If you will always be calling LoadStaff when you create a Database object you should place a call to LoadStaff() in the constructor for the Database class. If you won't be calling LoadStaff everytime then you should create a new StaffNames array.

            public Database() {
            LoadStaff();
            }

            or

            public Database() {
            StaffNames = new string[0]
            }

            HTH, James Sonork ID: 100.11138 - Hasaki "My words but a whisper -- your deafness a SHOUT. I may make you feel but I can't make you think." - Thick as a Brick, Jethro Tull 1972

            G Offline
            G Offline
            Gavin_Mannion
            wrote on last edited by
            #5

            I have tried that way and it does work but my idea was that I call the LoadStaff() function when my application starts and then I do not need to access the database again until they try update something. So as the SplashScreen is shown my application will load all the data needed into my arrays and then I can just read from them without accessing the database again. something like this. [code] //SplashScreen_Load Code Database LoadArrays = new Database(); InformationLabel.Text = "Loading Clinic Array....."; LoadArrays.LoadClinics(); InformationLabel.Text = "Loading Staff Array....."; LoadArrays.LoadStaff(); //So the 2 arrays are now populated //The main menu now loads and they choose Edit User from the menu //EditUser_Load Code Database sn = new Database(); int uBound = sn.StaffNames.GetUpperBound(0); [/code] Now I haven't called the the load function again because I do not want to access the database again. Am I going about this in all the wrong way? Thanks, PS:How do you change the bgColor where your code is displayed?

            J 1 Reply Last reply
            0
            • G Gavin_Mannion

              I have tried that way and it does work but my idea was that I call the LoadStaff() function when my application starts and then I do not need to access the database again until they try update something. So as the SplashScreen is shown my application will load all the data needed into my arrays and then I can just read from them without accessing the database again. something like this. [code] //SplashScreen_Load Code Database LoadArrays = new Database(); InformationLabel.Text = "Loading Clinic Array....."; LoadArrays.LoadClinics(); InformationLabel.Text = "Loading Staff Array....."; LoadArrays.LoadStaff(); //So the 2 arrays are now populated //The main menu now loads and they choose Edit User from the menu //EditUser_Load Code Database sn = new Database(); int uBound = sn.StaffNames.GetUpperBound(0); [/code] Now I haven't called the the load function again because I do not want to access the database again. Am I going about this in all the wrong way? Thanks, PS:How do you change the bgColor where your code is displayed?

              J Offline
              J Offline
              James T Johnson
              wrote on last edited by
              #6

              OK! Now I see where the problem is, you're confused about how properties work on a class. I'm going to discuss a smaller class to keep the example simple.

              public class MyClass {
              public int data;

              public MyClass() { }
              }

              Simple right? The class has one public member, an integer called data. Lets do some tests, and hopefully this will clear up your confusion.

              public void Tests() {
              MyClass foo = new MyClass();
              foo.data = 1;

              System.Console.WriteLine("foo = {0}", foo.data);

              MyClass bar = new MyClass();
              bar.data = 2;

              System.Console.WriteLine("foo = {0}", foo.data);
              System.Console.WriteLine("bar = {0}", bar.data);
              }

              You'll notice that foo is still 1 while bar is 2. The reason is that the data is stored with each instance of the class (an instance is a creation of that type in memory). But what if you have a value that needs to change in ALL instances of your type? Enter the static field/property. Simply make one change to the class definition public **static** int data. Now re-run the tests; foo and bar will both be 2 now. How does this apply to your circumstance? The arrays in your class are like data in the first example. Each array stays with that instance; so what happens when you create a new instance of your database class? A brand new instance of your arrays is created as well, this time without all the data. You now have a couple different tactics you can use. The easiest solution is to put the static keyword in the declaration with your arrays. This makes your data 'stick' with the type. The other solution is to use the same instance over and over again; one way of doing this is through the Singleton pattern, but I'll let you learn about that when you feel ready. Gavin_Mannion wrote: PS:How do you change the bgColor where your code is displayed? Secrets of the Jedi :-P Actually just do this with your code: <pre>code</pre>. HTH, James Sonork ID: 100.11138 - Hasaki "My words but a whisper -- your deafness a SHOUT. I may make you feel but I can't make you think." - Thick as a Brick, Jethro Tull 1972

              G 1 Reply Last reply
              0
              • J James T Johnson

                OK! Now I see where the problem is, you're confused about how properties work on a class. I'm going to discuss a smaller class to keep the example simple.

                public class MyClass {
                public int data;

                public MyClass() { }
                }

                Simple right? The class has one public member, an integer called data. Lets do some tests, and hopefully this will clear up your confusion.

                public void Tests() {
                MyClass foo = new MyClass();
                foo.data = 1;

                System.Console.WriteLine("foo = {0}", foo.data);

                MyClass bar = new MyClass();
                bar.data = 2;

                System.Console.WriteLine("foo = {0}", foo.data);
                System.Console.WriteLine("bar = {0}", bar.data);
                }

                You'll notice that foo is still 1 while bar is 2. The reason is that the data is stored with each instance of the class (an instance is a creation of that type in memory). But what if you have a value that needs to change in ALL instances of your type? Enter the static field/property. Simply make one change to the class definition public **static** int data. Now re-run the tests; foo and bar will both be 2 now. How does this apply to your circumstance? The arrays in your class are like data in the first example. Each array stays with that instance; so what happens when you create a new instance of your database class? A brand new instance of your arrays is created as well, this time without all the data. You now have a couple different tactics you can use. The easiest solution is to put the static keyword in the declaration with your arrays. This makes your data 'stick' with the type. The other solution is to use the same instance over and over again; one way of doing this is through the Singleton pattern, but I'll let you learn about that when you feel ready. Gavin_Mannion wrote: PS:How do you change the bgColor where your code is displayed? Secrets of the Jedi :-P Actually just do this with your code: <pre>code</pre>. HTH, James Sonork ID: 100.11138 - Hasaki "My words but a whisper -- your deafness a SHOUT. I may make you feel but I can't make you think." - Thick as a Brick, Jethro Tull 1972

                G Offline
                G Offline
                Gavin_Mannion
                wrote on last edited by
                #7

                Well I feel like I have tangled myself in a web I just ain't going to be getting out of :) Okay I have done as you said and I do understand everything that you have written down (minus the singleton thing but I don't wanna know ;) ) I have made my arrays static but now I cannot access them from my form. I get the following error message

                C:\Documents and Settings\gavin\My Documents\Visual Studio Projects\LTBRMaintenance\EditUser.cs(202): Static member
                'LTBRMaintenance.Database.StaffNames' cannot be accessed with an instance reference; qualify it with a type name instead

                And they are no longer in my intellisense dropdown. Here is what I have

                //Database.cs
                public class Database
                {
                public static string[] StaffNames;

                And in my EditUser_Load I have this

                //EditUser.cs
                Database sn = new Database();
                int uBound = sn.StaffNames.GetUpperBound(0);

                StaffNames is where the blue squiggly is squatting at the moment. Thanks for the help,

                J 1 Reply Last reply
                0
                • G Gavin_Mannion

                  Well I feel like I have tangled myself in a web I just ain't going to be getting out of :) Okay I have done as you said and I do understand everything that you have written down (minus the singleton thing but I don't wanna know ;) ) I have made my arrays static but now I cannot access them from my form. I get the following error message

                  C:\Documents and Settings\gavin\My Documents\Visual Studio Projects\LTBRMaintenance\EditUser.cs(202): Static member
                  'LTBRMaintenance.Database.StaffNames' cannot be accessed with an instance reference; qualify it with a type name instead

                  And they are no longer in my intellisense dropdown. Here is what I have

                  //Database.cs
                  public class Database
                  {
                  public static string[] StaffNames;

                  And in my EditUser_Load I have this

                  //EditUser.cs
                  Database sn = new Database();
                  int uBound = sn.StaffNames.GetUpperBound(0);

                  StaffNames is where the blue squiggly is squatting at the moment. Thanks for the help,

                  J Offline
                  J Offline
                  James T Johnson
                  wrote on last edited by
                  #8

                  Whoops! (famous last words) I forgot to mention this, when you have a static field you access it not by variablename.field, you access it by classname.field. So the last line should have been Database.StaffNames.GetUpperBound(0);. Completely my fault. James Sonork ID: 100.11138 - Hasaki "My words but a whisper -- your deafness a SHOUT. I may make you feel but I can't make you think." - Thick as a Brick, Jethro Tull 1972

                  G 1 Reply Last reply
                  0
                  • J James T Johnson

                    Whoops! (famous last words) I forgot to mention this, when you have a static field you access it not by variablename.field, you access it by classname.field. So the last line should have been Database.StaffNames.GetUpperBound(0);. Completely my fault. James Sonork ID: 100.11138 - Hasaki "My words but a whisper -- your deafness a SHOUT. I may make you feel but I can't make you think." - Thick as a Brick, Jethro Tull 1972

                    G Offline
                    G Offline
                    Gavin_Mannion
                    wrote on last edited by
                    #9

                    YAY YAY YAY YAY :) :) :)... It worked ;).... Thanks for the help maybe now I can get back on schedule with this project... ;P :-D ;P :-D ;P :-D ;P :-D Cheers, Gavin

                    J 1 Reply Last reply
                    0
                    • G Gavin_Mannion

                      YAY YAY YAY YAY :) :) :)... It worked ;).... Thanks for the help maybe now I can get back on schedule with this project... ;P :-D ;P :-D ;P :-D ;P :-D Cheers, Gavin

                      J Offline
                      J Offline
                      James T Johnson
                      wrote on last edited by
                      #10

                      Gavin_Mannion wrote: maybe now I can get back on schedule with this project... Good luck :) James Sonork ID: 100.11138 - Hasaki "My words but a whisper -- your deafness a SHOUT. I may make you feel but I can't make you think." - Thick as a Brick, Jethro Tull 1972

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups