你的位置:首页 > ASP.net教程

[ASP.net教程]winform(三)——更换主窗体例子


做一个登录窗口,登录成功时关闭form1,展示from2界面

 

1.主界面Login

namespace WindowsFormsApplication1{  public partial class Login : Form  {    public string username;//定义一个变量给子窗体传值    public Login()    {      InitializeComponent();    }    private void button1_Click(object sender, EventArgs e)    {      //取出用户名和密码      string uid = txtuid.Text;      string pwd = txtpwd.Text;      if (uid != "" && pwd != "")      {        LoginDA da = new LoginDA(); //连接数据库        if (da.DengLu(uid, pwd)) //登录查询        {          //将用户名赋值给成员变量username          username = uid;          //将该窗体的返回值变为OK          this.DialogResult = DialogResult.OK;          //将该窗体关闭          this.Close();        }        else        {          MessageBox.Show("用户名或密码错误!");        }      }      else      {        MessageBox.Show("用户名和密码不能为空!");      }    }    private void Login_Load(object sender, EventArgs e)    {    }  }}

2.Program.cs 修改主主窗体Login变为Main

namespace WindowsFormsApplication1{  static class Program  {    /// <summary>    /// 应用程序的主入口点。    /// </summary>    [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()    {      List<China> list = cda.Select("0001");      cmbsheng.DataSource = list;      cmbsheng.DisplayMember = "Name";      cmbsheng.ValueMember = "Code";    }    //填充市的方法    public void FillShi()    {      List<China> list = cda.Select(cmbsheng.SelectedValue.ToString());      cmbshi.DataSource = list;      cmbshi.DisplayMember = "Name";      cmbshi.ValueMember = "Code";    }    //填充区的方法    public void FillQu()    {      List<China> 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());    }  }}