Home > OS >  C# Run method from one form and display on another
C# Run method from one form and display on another

Time:01-08

I know this might sound basic, but as a beginner, I've been confused about the following:

I have two forms, the first one is where all connections and calculations are made, and the second one is where I want to display all the results.

FORM 1, Where I call to open the second form.

private void button_Click1(object sender, EventArgs e)
        {
            Button selected = sender as Button;
            openClientForm(new Form2());
        }

private Form activeForm = null;
        private void openClientForm( Form clientForm)
        {
            if (activeForm != null)
                activeForm.Close();
            activeForm = clientForm;
            clientForm.TopLevel = false;
            clientForm.FormBorderStyle = FormBorderStyle.None;
            clientForm.Dock = DockStyle.Fill;
            panelClientForm.Controls.Add(clientForm);
            panelClientForm.Tag = clientForm;
            clientForm.BringToFront();
            clientForm.Show();
        }

FORM 2)

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            //Form2_Load();
            updateText(txtCmdConsole, Form1.cmdres);
        }



        private void updateText(TextBox text, string strdata)
        {
            text.AppendText(strdata);

        }
    }

I have 1 question.

  1. When I open the second form, How can I run the Method updateText from form 1 and display the result in the second form? The reason I ask is that form1 should still be running in the background, and if a certain condition is met, I want the update text to be run in form 1(to get values from there) and update the second form.

CodePudding user response:

First, your activeForm should be of type Form2, not just Form, otherwise you cannot call specific methods from it (at least not easily). The code should look like this:

    private Form2 activeForm = null;
    private void openClientForm(Form2 clientForm)
    {
        if (activeForm != null)
            activeForm.Close();
        activeForm = clientForm;

    //...

Form2 can then offer a public interface to update certain text from the outside, with methods which don't expect internal controls as parameters. Something along the lines of

    // inside Form2
    public void UpdateCmdText(string strdata)
    {
        updateText(txtCmdConsole, strdata);
    }

Now you can call this method inside Form1 whereever you like:

    activeForm.UpdateCmdText(someNewResult)

Hope this helps.

  • Related