Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I would like to control Form1 from Form2

Tags:

c#

winforms

So I want basically the user to login in first in order to use the other form. However, my dilemma is that the login box is in Form2, and the main form is Form1.

if ((struseremail.Equals(username)) && (strpasswd.Equals(password)))
{
  MessageBox.Show("Logged in");
  form1.Visible = true;
  form1.WindowState = FormWindowState.Maximized;
}
else
{
  MessageBox.Show("Wow, how did you screw this one up?");
}

However, Form1 doesn't become visible, (since I launch it as visble = false) after they log in. Can someone help?

EDIT:

Brilliant response, but my problem is still here. I basically want to load Form2 First, (which is easy I run Form1 and set it to hide) But when Form2 is closed, I want Form1 to be closed as well.

private void Form2_FormClosing(Object sender, FormClosingEventArgs e)
{
  Form1 form1 = new Form1();
  form1.Close();
  MessageBox.Show("Closing");
}

this doesn't seem to work...

like image 858
smooth_smoothie Avatar asked Jun 30 '10 04:06

smooth_smoothie


1 Answers

You will need to pass the reference of one form to another, so that it can be used in the other form. Here I've given an example of how two different forms can communicate with each other. This example modifies the text of a Label in one form from another form.

Download Link for Sample Project

//Your Form1

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

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2(this);
        frm.Show();
    }

    public string LabelText
    {
        get { return Lbl.Text; }
        set { Lbl.Text = value; }
    }
}

//Your Form2

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

    private Form1 mainForm = null;
    public Form2(Form callingForm)
    {
        mainForm = callingForm as Form1; 
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.mainForm.LabelText = txtMessage.Text;
    }

    //Added later, closing Form1 when Form2 is closed.
    private void Form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        mainForm.Close();
    }
}

alt text
(source: ruchitsurati.net)

alt text
(source: ruchitsurati.net)

like image 114
this. __curious_geek Avatar answered Sep 22 '22 20:09

this. __curious_geek