• 0

Global variables available across multiple forms?


Question

Hey guys, just starting out with some C# programming, and atm I have the following,

frmMain - Form

frmAdd - Form

clsVideoLibrary - Class

frmMain declares a clsVideoLibrary, and loads everything into the class.. all fine and dandy.. however, the Add form adds in new items into the class.. atm, I have to pass everything back into frmMain and create a special function purely for the task (I guess it would depend on how my code is written), which is going to suck, as I'm going to basically redeclare this entire class inside of frmMain. Atm, I'm doing this by passing it frmMain.

Back in the old days of VB6, you used to just declare it as a global variable and stick it inside of a module, and all was well and everyone could access the class. But C# is a real poop about such things!

Is there any easy way to make the class available to other forms? As I'm going to have alot of classes and alot of forms, so it mightn't be entirely practical to pass the class files to the forms by reference or whatever.

w00t, 1234 posts :p

9 answers to this question

Recommended Posts

  • 0

Global variables don't exist in .NET, and rightfully so. It's a bad idea to use global variables, and if you're finding your code needs one, you should probably look at how your code is designed and change some things so you don't need a global variable.

If your Add form is a data collection window that returns data to your Main form, then you can (should?) add a method to your Main form that the Add form will use. You can also create an object to act as a container for the data between your two forms.

  • 0

So you're trying to open an AddForm from the MainForm that will allow the user to input a new video and add it to your Video library, yeah?

In which case id say you need another object... clsVideo. frmMain has an instance of clsVideoLibrary. frmAdd has a public instance of clsVideo. When the user clicks Save/Add in frmAdd you save the new video to the public instance of clsVideo. Then in your MainForm code where you open the AddForm you can do something like:

//Video library
clsVideoLibrary myVideoLibrary = new clsVideoLibrary();

//Open the AddForm
frmAdd objAddForm = new frmAdd();
objAddForm.ShowModal();

//Add the Video entered in the AddForm to the VideoLibrary
myVideoLibrary.Add( objAddForm.myNewVideo )

You'll probably also wanna do some checks to see if its null first - in case they press Cancel on the AddForm or something.

There are ways to do 'global variables' in .Net - Express showed one. But as John said, if you find yourself needing to use them - then you should be re-designing your code.

Oh... and VB6 sucks! :D

  • 0
  $phinX said:

So you're trying to open an AddForm from the MainForm that will allow the user to input a new video and add it to your Video library, yeah?

In which case id say you need another object... clsVideo. frmMain has an instance of clsVideoLibrary. frmAdd has a public instance of clsVideo. When the user clicks Save/Add in frmAdd you save the new video to the public instance of clsVideo. Then in your MainForm code where you open the AddForm you can do something like:

//Video library
clsVideoLibrary myVideoLibrary = new clsVideoLibrary();

//Open the AddForm
frmAdd objAddForm = new frmAdd();
objAddForm.ShowModal();

//Add the Video entered in the AddForm to the VideoLibrary
myVideoLibrary.Add( objAddForm.myNewVideo )

You'll probably also wanna do some checks to see if its null first - in case they press Cancel on the AddForm or something.

There are ways to do 'global variables' in .Net - Express showed one. But as John said, if you find yourself needing to use them - then you should be re-designing your code.

Oh... and VB6 sucks! :D

Hmm, I like, I like alot. :) I have a struct defined for Video already so should be easy to implement. :)

Yeah... but global variables make 'sense'. :( And don't knock VB6, was a great language :( I dunno, I don't like like the idea of having my code thrown all over the place. Inside AddForm it writes the new element to the XML doc, and then adds it to clsVideoLibrary to save my reloading... which I personally see as being related code that should be lumped together....maybe I really should just rip everything out of AddForm and write everything in frmMain? Hmmmmmm

  • 0

Your code isn't "thrown all over the place" in .NET. Rather the opposite; it's organized into objects that make it easier to do your work. Sometimes this may take a little extra work, but in the end, it simplifies things immensely. Global variables make sense to you now, but if/when you learn .NET, you'll discover how truly convoluted VB6 is.

  • 0

Ok, so I have it all working, but I'm getting some warnings,

frmAdd.Add -> Add it!

		public VideoCollection.VideoItem VideoToAdd = new VideoCollection.VideoItem();

		private void btnAdd_Click(object sender, EventArgs e)
		{
			VideoToAdd.CatID = 1;
			VideoToAdd.Title = txtTitle.Text;
			VideoToAdd.Location = txtLocation.Text;
			VideoToAdd.ImageID = Int32.Parse(txtImage.Text);
			this.Close();
		}

frmMain.Show Add Form button

 private void btnShowAdd_Click(object sender, EventArgs e)
		{
			frmAdd MyAddForm = new frmAdd();
			MyAddForm.ShowDialog();

//......XML + collection code here
			   XMLNewAttribute.Value = MyAddForm.VideoToAdd.CatID.ToString();

Atm, I get the following warning,

  Quote

Warning 1 Accessing a member on 'VideoLibrary.frmAdd.VideoToAdd' may cause a runtime exception because it is a field of a marshal-by-reference class C:\Documents and Settings\Phillip\My Documents\Visual Studio 2005\Projects\VideoLibrary\VideoLibrary\Form1.cs 193

Any ideas what that is all about? :\

  • 0

	public struct VideoItem
	{
		public int ID;
		public int CatID;
		public string Title;
		public string Location;
		public int ImageID;
	}

:)

Ok, copying it to a local variable seems to do the trick. Why though? :\

Edited by Pc_Madness
  • 0
  Pc_Madness said:

	public struct VideoItem
	{
		public int ID;
		public int CatID;
		public string Title;
		public string Location;
		public int ImageID;
	}

:)

Ok, copying it to a local variable seems to do the trick. Why though? :\

If it is global then why not make it a class? That way it will be passed around as a reference. Structs will be passed by value.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Here's why it makes sense to name it iOS 26 and why it doesn't by Aditya Tiwari It has been almost 18 years since Apple launched the first version of its popular mobile operating system alongside the original iPhone. Recent reports and rumors circulating on the web suggest that the company is all set to unveil a major overhaul for iOS 19 at this year's WWDC keynote. There is something that baffled many when they found that the Cupertino giant is reportedly planning to rename iOS 19 to iOS 26. Yes, a company like Apple skipping eight versions for iOS is enough to leave users with a "why?" expression on their face. However, even if Apple pulls it off, there are two sides to the coin. Why it makes sense to call it iOS 26 There are several reasons why calling it iOS 26 instead of iOS 19 isn't as weird as it sounds. To begin with, it's something that has been done in the past. Samsung is a well-known example when we think about renaming device lineups and skipping version numbers. Samsung launched the Galaxy S20 series in 2020. But what was its predecessor? Galaxy S19? No, it was the Galaxy S10. The South Korean giant renamed its device lineup and aligned it with the year of launch, jumping ten versions in the process. So, someone viewing a Galaxy S23 can easily determine that the device was launched in 2023. It also gives them a feeling that they are using the 'latest and greatest' product. On the flip side, a device from the previous year may feel outdated, potentially motivating them to upgrade. Skipping version numbers isn't fun and games for everyone. Microsoft became the butt of jokes when it skipped Windows 9 and announced that Windows 8.1 will be upgraded to Windows 10 (that too in 2015). Windows 10 was thought to be "the last version of Windows", but things turned out differently. Apple's case would be a bit different, where the iOS version number is one year ahead. So, iOS 26 will release in 2025, iOS 27 in 2026, and so on. This approach is similar to how game companies like Electronic Arts name their gaming titles. Although it may seem off track, the naming scheme aligns with Apple's development schedule. The company typically announces new iOS versions at WWDC in June and rolls them out to the public in the fall season. After that, it continues to push incremental updates through the following year. In other words, a particular iOS version lives on your iPhone for a quarter of the launch year and about nine to ten months in the following year. Meanwhile, Samsung releases new Galaxy S devices at the start of the year, so it makes more sense to align their name with the current year. Not just iOS 26, reports said that Apple will streamline its confusing software naming system by renaming almost all of its operating systems to a single version. So, there will be iPadOS 26, macOS 26, tvOS 26, and watchOS 26 instead of iPadOS 19, macOS 16, tvOS 12, and so on. While the big move will make things easier for users, it will also highlight the work Apple has been doing to unify its software experience across devices. iOS and iPadOS have been related to each other from the beginning, but macOS gained ARM support in 2020 and began incorporating iOS-like UI elements. Apple has already developed a suite of Continuity features that enable different Apple devices to work together. macOS 14 Sonoma further bridged the gap between iPhone and Mac in 2023 with a revamped widgets picker UI, which allows access to and syncing with widgets stored on your iPhone. New widgets introduced in macOS 14 are interactive, similar to those on iPhone. They let you do stuff like checking off reminders, playing or pausing media, accessing smart home controls, and more. Apple's iOS 26/iOS 19 would be the second major naming shake-up in the history of iOS. The first one was when Apple renamed the operating system from iPhone OS to iOS in June 2010. iOS 26 is expected to be the biggest update in years, reportedly featuring a 'dramatic' glass-like UI overhaul, a revamped Camera app, live translation for AirPods, a new gaming app, and a new set of accessibility features. The glass-like design, first introduced on Apple's Vision Pro headset, is expected to make its way to tvOS and watchOS. Why doesn't it make sense to call it iOS 26 It already feels a bit awkward when you realize that the iPhone 16 runs iOS 18, for whatever reason, when the first iterations of both iPhone and iOS arrived in the same year. Adding eight more digits to the iOS version number will make it sound even weirder. The 19th generation of iPhone's operating system will be called iOS 26. Imagine buying an iPhone 17 later this year, and it runs iOS 26 out of the box. However, there are a couple of things Apple can do to tone down the awkwardness. Perhaps Apple can rename the iPhone series and start calling it iPhone 26 to match its software counterpart. A far-fetched and even more unlikely option is to drop version numbers from the iPhone's name entirely. Apple is already doing it for its tablets (iPad, iPad Pro, and iPad Air) and its Mac computers. Therefore, it won't be an issue once the users absorb the initial shock of the announcement. But we can't ignore that not having a version number tied to a product has its downsides. These are all speculations anyway. Whatever happens, Apple fans will get over it and learn to live with it, like they are living with the hopes of an upgraded Siri and AirPower to charge their Apple devices together.
    • I'd prefer the disclaimer being more transparent by putting it above the article.
    • dBpoweramp Music Converter 2025-06-05 by Razvan Serea Audio conversion perfected, effortlessly convert between formats. dBpoweramp contains a multitude of audio tools in one: CD Ripper, Music Converter, Batch Converter, ID Tag Editor and Windows audio shell enhancements. Preloaded with essential codecs (mp3, wave, FLAC, m4a, Apple Lossless, AIFF), additional codecs can be installed from [Codec Central], as well as Utility Codecs which perform actions on audio files. After 21 days the trial will end, reverting to dBpoweramp Free edition (learn the difference between Reference and dBpoweramp Free, here). dBpoweramp is compatible with Windows 10, 8, 7, Vista, both 32 and 64 bit. dBpoweramp Music Converter features: Convert audio files with elegant simplicity. mp3, mp4, m4a (iTunes / iPod), Windows Media Audio (WMA), Ogg Vorbis, AAC, Monkeys Audio, FLAC, Apple Lossless (ALAC) to name a few! Multi CPU Encoding Support Rip digitally record audio CDs (with CD Ripper) Batch Convert large numbers of files with 1 click Windows Integration popup info tips, audio properties, columns, edit ID-Tags DSP Effects such as Volume Normalize, or Graphic EQ [Power Pack Option] Command Line Encoding: invoke the encoder from the command line DSP Effects - process the audio with Volume Normalize, or Sample / Bit Rate Conversion, with over 30 effects dBpoweramp is a fully featured mp3 Converter dBpoweramp integrates into Windows Explorer, an mp3 converter that is as simple as right clicking on the source file >> Convert To. Popup info tips, Edit ID-Tags are all provided. dBpoweramp Music Converter 2025.06.05 changelog: Darkmode added Core Converter Debug log dumps ID Tags written VST Effect Folders dialog fixed missing InitCommonControls would not show correctly FLAC/Ogg/Opus/etc - allows editing of CDTOC ID Tag CD Ripper secure ripping log where shows TOC was not showing CD Extra correctly CD Ripper was incorrectly setting data track length on main display (for certain drives) CD Ripper internally better handling of corrupt TOCs CD TOC to Tag was incorrectly adding 150 to CD Extra disc CD Ripper shows "AccurateRip Unconfigured" in rip status rather than "not in accuraterip" if unconfigured CD Ripper art paste accepts https CueSheet added as standard - log file written to same folder as cue and folder.jpg AIFF internal code merge (macos >> windows) Download: dBpoweramp Music Converter R2025.06.05 | 82.2 MB (Shareware) View: dBpowerAMP Music Converter Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Staged. It's a requirement that vehicles are strapped down to the bed. Usually wheel and/or chassis tie downs are used. That appears to just be on the winch.
  • Recent Achievements

    • Week One Done
      abortretryfail earned a badge
      Week One Done
    • First Post
      Mr bot earned a badge
      First Post
    • First Post
      Bkl211 earned a badge
      First Post
    • One Year In
      Mido gaber earned a badge
      One Year In
    • One Year In
      Vladimir Migunov earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      495
    2. 2
      snowy owl
      255
    3. 3
      +FloatingFatMan
      252
    4. 4
      ATLien_0
      227
    5. 5
      +Edouard
      191
  • Tell a friend

    Love Neowin? Tell a friend!