Access to main form objects in other .cs files

It is easy to access sub-window objects from the main file, because we still need to create an auxiliary window. So something like this:

SubForm subform = new SubForm();
if (subform.ShowDialog() == DialogResult.OK)
{
    text = subform.textBox1.Text; 
    //...
}

But I have some problems editing combobox (located inside the main form) using a sub-cs file. I can’t just create a new main window. I edited the Program.cs file:

static class Program
    {
        public static MainForm mainform; //main window reference
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(mainform = new MainForm());
        }
    }

Now I can access combobox:

Program.mainform.comboCurves.Items.Add("test");

Is this the best solution for this?

+4
source share
1 answer

You can also pass a link to your main form directly to your subform, at least your main form will not be available for your entire application:

MainWindow.cs:

SubForm subform = new SubForm(this);

SubForm.cs:

public partial class SubForm : Form
{
    private MainForm mainForm;
    public SubForm(MainForm mainForm)
    {
        InitializeComponent();
        this.mainForm = mainForm;
    }
}

, , mainForm.comboCurves.Items.Add( "test" );


, , , :

public partial class MainForm : Form, IRestrictedInterfaceOfMainForm
{
    public void AddStuff(string stuff)
    {
        comboCurves.Items.Add(stuff);
    }
}

public interface IRestrictedInterfaceOfMainForm
{
    void AddStuff();
}

public partial class SubForm : Form
{
    private IRestrictedInterfaceOfMainFormmainForm mainForm;
    public SubForm(IRestrictedInterfaceOfMainFormmainForm mainForm)
    {
        InitializeComponent();
        this.mainForm = mainForm;
    }
}

, , MainForm. , comboCurves , .


, , , .

+4

All Articles