我是c#语言的新手,我有一个名为Mainwindow
的表单:
public partial class MainWindow : Window
{
ConnectionManager DatabaseConnect = new ConnectionManager();
LoginController LoginControl = new LoginController();
public MainWindow()
{
InitializeComponent();
}
private void Done_btn_Click(object sender, RoutedEventArgs e)
{
LoginControl.Login();
}
private void Close_btn_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DatabaseConnect.ConnectDatabase();
Username_txtbox.Focus();
}
private void Username_txtbox_KeyDown(object sender, KeyEventArgs e)
{
LoginControl.KeyEnter(e);
}
private void Password_txtbox_KeyDown(object sender, KeyEventArgs e)
{
LoginControl.KeyEnter(e);
}
private void Password_txtbox_KeyDown_1(object sender, KeyEventArgs e)
{
LoginControl.KeyEnter(e);
}
}
LoginController类
class LoginController
{
private ConnectionManager DatabaseConnect = new ConnectionManager();
public void KeyEnter(KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Login();
}
}
public void Login()
{
MainWindow MainWindowPage = new MainWindow();
DatabaseConnect.ConnectDatabase();
System.Text.RegularExpressions.Regex EmailOnly = new Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
//Validates the textbox if it does not match the Regular expression of email address.
if (!EmailOnly.IsMatch(MainWindowPage.Username_txtbox.Text))
{
MessageBox.Show("Invalid email address!");
return;
}
else
{
if (MainWindowPage.Username_txtbox.Text.Length == 0 || MainWindowPage.Password_txtbox.Password.Length == 0)
{
MessageBox.Show("Enter on the login fields.");
}
if (MainWindowPage.Username_txtbox.Text != "" && MainWindowPage.Password_txtbox.Password != "")
{
DatabaseConnect.SqlStringQuery = "SELECT * FROM login_tbl WHERE user_email = '" + MainWindowPage.Username_txtbox.Text + "' AND password = '" + MainWindowPage.Password_txtbox.Password + "'";
DatabaseConnect.Getdata();
if (DatabaseConnect.SQLDR.HasRows == true)
{
DatabaseConnect.SQLDR.Close();
AdminForm AdminForm = new AdminForm();
AdminForm.Show();
MainWindowPage.Close();
}
else
{
DatabaseConnect.SQLDR.Close();
MessageBox.Show("Invalid user account!");
}
}
}
}
}
我尝试将Login()代码放在正确验证的主窗口中,然后我将Login()置于LoginController类中,但似乎该类无法在主窗口中检索文本框的值显示"无效的电子邮件地址"即使我在maindow文本框中添加了必要的值
有什么想法吗?
答案 0 :(得分:1)
您的问题是,您在MainWindow
方法中创建了一个名为MainWindowPage
的新Login
,其Username_txtbox
的默认文字为空(我猜是这样)。 MainWindowPage
不是您程序的主窗口。您必须在Login
方法中传递当前主窗口。修改您的代码如下(只需稍加修改):
public void Login(MainWindow MainWindowPage)
{
DatabaseConnect.ConnectDatabase();
//....
}
和...
private void Done_btn_Click(object sender, RoutedEventArgs e)
{
LoginControl.Login(this);
}