Passing Parameters from the Login Form to the Main Form

20130627065507 The holiday is almost here — what to do over the break? We just started an SQL Server course. I made a roll-call app before, but without a database, so its features were limited. I’m planning to build a more powerful class roll-call app over the holiday.

Last night I made two windows: a login window and a main window. Let’s look at the code. Program.cs in the project starts the login window first, then the main window:

namespace 点兵点将2._0 { static class Program { ///

/// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); LoginForm loginForm = new LoginForm(); if (loginForm.ShowDialog() == DialogResult.OK) { Application.Run(new MainForm()); } } } }

But then I got stuck — why? After the login window verifies successfully, how does the main form know who logged in? How do I pass the parameters over?

My mind went blank. Then I noticed the parentheses in Application.Run(new MainForm());MainForm(). Since I taught myself C, I’m used to procedural style; I still prefer calling them functions rather than methods. Aren’t those functions? They take parameters in the parentheses. The words “constructor” flashed before my eyes.

What is a constructor? I won’t explain it in detail here — it’s for initialization when you new an object.

In MainForm.cs:

public partial class MainForm : Form { public string zhanghao = “未知账号”; public string xingming = “未知账号”; public string kemu = “未知账号”; public MainForm(string zh,string xm,string km) { InitializeComponent(); zhanghao = zh; xingming = xm; kemu = km; } }

Just add the parameters you need to pass into the constructor public MainForm(), and assign them to the fields of the main form. That’s it. It all became clear — I really just haven’t written enough code; how did I not think of the constructor right away?