Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

c# - I would like to control Form1 from Form2

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...