为什么我的Windows窗体应用程序上的按钮没有工作?
为什么我的Windows窗体应用程序上的按钮没有工作?
我正在制作一个ATM机,首先要编程的是登录界面。为了定义用户,我创建了一个User类,该类由id、用户名、密码、储蓄账户和支票账户组成。在我的窗体中,我创建了两个按钮,一个用于执行登录,另一个用于关闭程序。以下是我的Windows窗体的代码:
using 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; namespace ATM_Project { public partial class Form1 : Form { Listusers = new List (); int attempts = 3; public Form1() { new User() { id = 0, userName = "user1", password = "password123", savingsAcct = 2000, checkAcct = 2500 }; new User() { id = 1, userName = "user2", password = "password234", savingsAcct = 3000, checkAcct = 4500 }; new User() { id = 2, userName = "user3", password = "pass345", savingsAcct = 3000, checkAcct = 5000 }; InitializeComponent(); } private void exitbtn_Click(object sender, EventArgs e) { this.Close(); //此按钮用于关闭应用程序 } private void loginbtn_Click(object sender, EventArgs e) { verification(); } public void verification() { for (int i = 0; i < users.Count; i++) { while (attempts != 0) { if (textBox1.Text == users[i].userName && textBox2.Text == users[i].password) //检查用户名和密码是否匹配。 { MessageBox.Show("Your password is correct!"); break; } else { MessageBox.Show("Error. Your username or password are incorrect!"); attempts = attempts - 1; } } } } } }
我将对象放置在一个列表中,并使用for循环遍历该列表,将用户在第一个文本框中输入的内容与第i个位置的用户名进行比较,并将用户在第二个文本框中输入的内容与第i个位置的密码进行比较。如果匹配,则应弹出一个消息告诉我密码正确。如果错误,则应告诉我密码错误,并在三次尝试后停止工作。我创建了一个名为verification的公共void,在其中进行所有测试,并在登录按钮中调用它。然而,它没有起作用。当我在文本框中输入内容并点击登录按钮时,什么都不会发生。但是退出按钮可以正常工作。有没有可能忘记了某些东西?为什么会发生这种情况?
为什么我的Windows窗体应用程序上的按钮不起作用?
看起来你正在定义新的用户,但没有将他们添加到列表中。
所以你正在循环遍历0个用户。
你可以将Form1()更改为:
public Form1() { users.add(new User() { id = 0, userName = "user1", password = "password123", savingsAcct = 2000, checkAcct = 2500 }); users.add(new User() { id = 1, userName = "user2", password = "password234", savingsAcct = 3000, checkAcct = 4500 }); users.add(new User() { id = 2, userName = "user3", password = "pass345", savingsAcct = 3000, checkAcct = 5000 }); InitializeComponent(); }
还要注意,this.Close()只关闭窗口,而不是应用程序。如Winforms: Application.Exit vs Enviroment.Exit vs Form.Close中所解释的那样。
我认为这个验证版本可能更有意义:
public void verification() { if (textBox1.Text == users[i].userName && textBox2.Text == users[i].password) { MessageBox.Show("Your password is correct!"); } else { MessageBox.Show("Error. Your username or password are incorrect!"); attempts -= 1; } if(attempts == 0) { Environment.Exit(); } }
以上就是问题出现的原因和解决方法。