سؤال

I have two files, one is the main form file which is generated when you create a new WinForms project in VS, and another one which contains a class I want to use in the form file. How do I access the Class file and use that class in the Form file? I think this project is going to be taking up a lot of different classes and I don't want them clogging up the Form file.

namespace The_World //in the form file
{
    public partial class The_Kingdom : Form
    {
        public The_Kingdom()
        {
            King foo = new King();
            InitializeComponent();
        }
    }
}

// Below this is in the "The King" file

namespace The_World
{
    public class King
    {
        bool goodKing; //just for an example
    }
}

-- Edit -- Sorry to have bothered everyone, but thanks for assisting me.

هل كانت مفيدة؟

المحلول

You can add class to your project by right click on the project in solution explorer and go to Add> class. give name to your class and add the methods you need.

public class Myclass
{
 public void MyMethod()
 {
 }
}

Than you need to call method from Main form like below , here on button click we will call the method.

public class form1
{
   public void button_click(object sender, EventArgs e)
   {
       Myclass myclass = new Myclass();
       myclass.MyMethod();
   }
}

You better follow some tutorials and books.

http://www.homeandlearn.co.uk/csharp/csharp_s10p1.html

نصائح أخرى

You don't have to include files if that's what you mean. Simply refer to the class in the "other" file from your form and that's it.

Maybe you can clarify what you need?

You have to make a decision about how you want to integrate the content of the file. The main choices are

1) Create instance methods on a class defined in the second file. Then create an instance of the class and call the methods on the instance

2) Create static methods on a class that you can call directly at the type level.

Both approaches are valid, but each unique problem determines which one is better..

//your class cs file, e.g. Something.cs
class Something
{
    ...
}


//Form class, form1.cs
Something sth=new Something();
sth.SomeMethod();
  • Make sure your class is in the same namespace as the winform;
  • if not, add "using xyz" in your form class, where xyz is the namespace of the class you want to access;
  • create an instance either as a field of the form class or in some method
  • call its method or acess the properties
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top