我正在创建一个登录屏幕,用于我被指派制作的测验游戏的课程作业。我在C#(windows表单应用程序)中进行此测验。
以下是我之前的代码:
entersing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace frmSplashScreen
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
int signUpPressed = 0;
private void button1_Click(object sender, EventArgs e)
{
string[] userdetails = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "UserDetails.txt");
foreach (string user in userdetails)
{
string[] splitDetails = user.Split(':');
Login.username = splitDetails[0];
Login.password = splitDetails[1];
label1.Text = Login.username;
label2.Text = Login.password;
if ((txtUsername.Text == Login.username) && (txtPassword.Text == Login.password))
{
MessageBox.Show("Welcome " + Login.username);
this.Hide();
frmMainMenu menu = new frmMainMenu();
menu.Show();
break;
}
else
{
if ((txtUsername.Text == Login.username) && (txtPassword.Text != Login.password))
{
MessageBox.Show("Password incorrect");
txtPassword.Text = "";
}
else
{
MessageBox.Show("Username incorrect");
txtUsername.Text = "";
txtPassword.Text = "";
}
break; //Remove this break it's not needed
}
}
}
}
}
此处还有.txt文件,它正在从以下位置读取登录详细信息:
Ryan:password
Username:password
我的问题是当我点击登录按钮(button1)时,它只是读取UserDetails.txt的第一行,当我输入 Ryan 和密码时文本框,它工作正常。但是,当我在文本框中键入用户名和密码时,它会在消息框中显示错误消息“用户名不正确”。 此外,“登录”是一个存储用户名和密码
的变量的类非常感谢任何帮助。 感谢。
答案 0 :(得分:0)
foreach循环中的每个分支都以break;
结束,您永远不会进入第二个条目。将第二个中断移动到“密码不正确”,如果用户名不匹配,则允许循环继续,也许另一个中断。如果找到匹配项,请在循环后检查。 (在新方法break;
中将return username;
替换为CheckAndGetUser()
时,这可能会更容易。)