passing data between two forms using properties

前端 未结 1 507
花落未央
花落未央 2021-01-26 12:51

I am passing data between 2 windows forms in c#. Form1 is the main form, whose textbox will receive the text passed to it from form2_textbox & display it in its textbox (for

相关标签:
1条回答
  • 2021-01-26 13:31

    I know this is a (really) old question, but hell..

    The "best" solution for this is to have a "data" class that will handle holding whatever you need to pass across:

    class Session
    {
        public Session()
        {
            //Init Vars here
        }
        public string foo {get; set;}
    }
    

    Then have a background "controller" class that can handle calling, showing/hiding forms (etc..)

    class Controller
    {
        private Session m_Session;
        public Controller(Session session, Form firstform)
        {
            m_Session = session;
            ShowForm(firstform);
        }
    
        private ShowForm(Form firstform)
        {
            /*Yes, I'm implying that you also keep a reference to "Session"
             * within each form, on construction.*/
            Form currentform = firstform(m_Session);
            DialogResult currentresult = currentform.ShowDialog();
            //....
    
            //Logic+Loops that handle calling forms and their behaviours..
        }
    }
    

    And obviously, in your form, you can have a very simple click listener that's like..

    //...
        m_Session.foo = textbox.Text;
        this.DialogResult = DialogResult.OK;
        this.Close();
    //...
    

    Then, when you have your magical amazing forms, they can pass things between each other using the session object. If you want to have concurrent access, you might want to set up a mutex or semaphore depending on your needs (which you can also store a reference to within Session). There's also no reason why you cannot have similar controller logic within a parent dialog to control its children (and don't forget, DialogResult is great for simple forms)

    0 讨论(0)
提交回复
热议问题