做一个登录窗口,登录成功时关闭form1,展示from2界面
1.主界面Login
1 namespace WindowsFormsApplication1 2 { 3 public partial class Login : Form 4 { 5 public string username;//定义一个变量给子窗体传值 6 public Login() 7 { 8 InitializeComponent(); 9 }10 11 private void button1_Click(object sender, EventArgs e)12 {13 //取出用户名和密码14 string uid = txtuid.Text;15 string pwd = txtpwd.Text;16 17 if (uid != "" && pwd != "")18 {19 LoginDA da = new LoginDA(); //连接数据库20 if (da.DengLu(uid, pwd)) //登录查询21 {22 23 //将用户名赋值给成员变量username24 username = uid;25 //将该窗体的返回值变为OK26 this.DialogResult = DialogResult.OK;27 //将该窗体关闭28 this.Close();29 30 }31 else32 {33 MessageBox.Show("用户名或密码错误!");34 }35 }36 else37 {38 MessageBox.Show("用户名和密码不能为空!");39 }40 }41 42 private void Login_Load(object sender, EventArgs e)43 {44 45 }46 }47 }
2.Program.cs 修改主主窗体Login变为Main
namespace WindowsFormsApplication1{ static class Program { ////// 应用程序的主入口点。 /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //造一个登录窗体 Login log = new Login(); if (log.ShowDialog() == DialogResult.OK) { Application.Run(new Main(log.username));//main窗体的构造方法 } } }}
3.Main窗体
namespace WindowsFormsApplication1{ public partial class Main : Form { private string uid;//造一个变量接收Login窗体的值 private ChinaDA cda; public Main() { InitializeComponent(); } public Main(string username) { InitializeComponent(); uid = username; cda = new ChinaDA();//连接数据库 } private void Main_Load(object sender, EventArgs e) { label1.Text = uid;//把接收到的值传给label1显示一下 //填充省的下拉列表 FillSheng(); //填充市的下拉列表 FillShi(); //填充区的下拉列表 FillQu(); } private void cmbsheng_SelectedIndexChanged(object sender, EventArgs e) { //填充市的下拉列表 FillShi(); //填充区的下拉列表 FillQu(); } private void cmbshi_SelectedIndexChanged(object sender, EventArgs e) { //填充区的下拉列表 FillQu(); } //填充省的方法 public void FillSheng() { Listlist = cda.Select("0001"); cmbsheng.DataSource = list; cmbsheng.DisplayMember = "Name"; cmbsheng.ValueMember = "Code"; } //填充市的方法 public void FillShi() { List list = cda.Select(cmbsheng.SelectedValue.ToString()); cmbshi.DataSource = list; cmbshi.DisplayMember = "Name"; cmbshi.ValueMember = "Code"; } //填充区的方法 public void FillQu() { List list = cda.Select(cmbshi.SelectedValue.ToString()); cmbqu.DataSource = list; cmbqu.DisplayMember = "Name"; cmbqu.ValueMember = "Code"; } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(cmbsheng.SelectedValue.ToString()); } }}