首页 > 解决方案 > Visual C# 如果文本框等于 1 打开表单 1 如果文本框等于 2 打开表单 2

问题描述

我为我在学校的工作创建了一个登录页面,但我有点卡住了,我需要它,以便如果学生登录它会显示学生表单,如果教师登录它会显示教师表单。

        private void btnSignIn_Click(object sender, EventArgs e)
    {
        if (txtUser.Text == "Student" & txtPass.Text == "GPSC1" || txtUser.Text == "Staff" & txtPass.Text == "GPSC2")

            MessageBox.Show("Success");

        else
            MessageBox.Show("Error");

        if (txtUser.Text == "Student" & txtPass.Text == "GPSC1")
            this.Hide();
        StudentForm studentForm = new StudentForm();
        studentForm.ShowDialog();
        this.Close();

        if (txtUser.Text == "Staff" & txtPass.Text == "GPSC2")
            this.Hide();
        TeacherForm teacherForm = new TeacherForm();
        teacherForm.ShowDialog();
        this.Close();


    }

标签: c#

解决方案


您应该添加大括号以创建新范围,这样您就可以在一个语句中执行多个if语句。

例如:

private void btnSignIn_Click(object sender, EventArgs e)
{
    if (txtUser.Text == "Student" && txtPass.Text == "GPSC1")
    //                            ^^  use &&   (& suits better for bitwise)
    {
        MessageBox.Show("Success");
        this.Hide();
        StudentForm studentForm = new StudentForm();
        studentForm.ShowDialog();
        this.Close();
    }
    else
        if(txtUser.Text == "Staff" && txtPass.Text == "GPSC2")
        {
            MessageBox.Show("Success");
            this.Hide();
            TeacherForm teacherForm = new TeacherForm();
            teacherForm.ShowDialog();
            this.Close();
        }
        else
            MessageBox.Show("Error");
}

推荐阅读