Reference external class from Windows Form

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • danphillips1977
    New Member
    • Apr 2010
    • 2

    Reference external class from Windows Form

    Hopefully this hasn't been asked already - apologies if so

    I have a Windows Form running inside C# - built using the form designer

    I've built a number of methods inside the form Events which I now want to strip out into External class files (in order to try and make the app a bit more architecturally correct so to speak).

    To do this, I have created a new Project which I've added to the Solution.
    I've managed to connect the class to the form by building the .cs file and then referencing the class in my form method - example reference:

    ClearDetails cls = new ClearDetails();

    So, if I have this right, I should be able to add my namespace to my form code, then specify the above code inside the Form Load event, then ultimately, the cls object created above should be available inside any event within the form?

    However, this does not appear to be the case - the cls object is only available in the Form Load event?

    My Class file contains a Public ClearDetails constructor along with a public method. The class file also uses the System.Windows. Forms namespace. I am using VS 2008 with Framework 3.5

    If anyone could help or point me in the right direction, your help would be greatly appreciated

    Many Thanks,
    Dan
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    Its a matter of scope. In easy terms: A variable only exists between the { and }
    If you give it life in the Load() {} then it dies at the end of the Load() {}
    But if you give it life at the Class() {} then it doesn't die until the end of the class () {}

    So move the creation of the variable up a little, but set its value in the load()

    Code:
    namespace blahblah
    {
       class  widget
       {
          ClearDetails myDetails; // Scope lifetime of the entire Widget class
    
          Form1_load
          {
               myDetails = new ClearDetails(); // assigned a value
          }
    
       }
    }

    Comment

    • danphillips1977
      New Member
      • Apr 2010
      • 2

      #3
      Many Thanks

      Many thanks tlhintoq

      Understand. That all works a treat now

      Comment

      Working...