Using and instance of a class on two forms

2019-03-01 02:26发布

I am struggling to get my head around the following. I current have three forms, my main and one main class.

public partial class frmMain : Form
{
    public frmMain()
    {
        InitializeComponent();
    }
}

public partial class frmSuppliers : Form
{
    public frmSuppliers()
    {
        InitializeComponent();
    }
}

public partial class frmCustomers : Form
{
    public frmCustomers()
    {
        InitializeComponent();
    }
}

In my main program I have:

 public class Program
 {
        public StockControl StockSystem = new StockControl("The Book Shop", 20);
 }

I want to be able to access the methods from StockControl in frmSuppliers and frmMain.

I know this may be a N00b question - but its been bugging me all day!

标签: c# winforms oop
3条回答
甜甜的少女心
2楼-- · 2019-03-01 02:58

You need to pass it to the other forms as a constructor parameter, then store it in a private field.

查看更多
闹够了就滚
3楼-- · 2019-03-01 03:02

declare it static

public static StockControl StockSystem = new StockControl("The Book Shop", 20);

and use as

Program.StockSystem 
查看更多
聊天终结者
4楼-- · 2019-03-01 03:03

You should add a field of type StockControl to each of your forms, and make it public, or add getter/setter to it. This means adding the following lines to each one of your forms:

private StockControl _stockCtrl;
public StockControl StockCtrl
{
   get { return _stockCtrl; }
   set { _stockCtrl = value; }
}

The in the cod of each form you can access your StockControl. But it will be empty (i.e. null) if you don't assign it something. This is something I'd do before opening the form. If you are in your main method:

frmSuppliers frmToOpen = new frmSuppliers();
frmSuppliers.StockCtrl = StockSystem;
frmSuppliers.Show();
查看更多
登录 后发表回答