我正在制作一个与MySQL连接的c#登录系统,到目前为止它还不错。如何让这段代码变得更好?它的代码太多了。
if (string.IsNullOrEmpty(textBoxUsername.Text))
{
//Focus box before showing a message
textBoxUsername.Focus();
MessageBox.Show("Enter your username", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
//Focus again afterwards, sometimes people double click message boxes and select another control accidentally
textBoxUsername.Focus();
return;
}
else if (string.IsNullOrEmpty(textBoxPassword.Text))
{
textBoxPassword.Focus();
MessageBox.Show("Enter your password", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
textBoxPassword.Focus();
return;
}
答案 0 :(得分:0)
您可以创建一个私有函数,例如:
private bool isValidTextBox(TextBox box, string message)
{
if(string.IsNullOrEmpty(box.Text))
{
MessageBox.Show(message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
box.Focus();
return false;
}
return true;
}
然后,使用如下函数:
if(!isValidTextBox(textBoxUsername, "Enter your username"))
return;
else if(!isValidTextBox(textBoxPassword, "Enter your password"))
return;
答案 1 :(得分:0)
您可以简单地将其移动为通用逻辑并重复使用以下代码。
private bool IsValidateTextBoxSuccess(TextBox textBox, string messageString)
{
if (string.IsNullOrEmpty(textBox.Text.Trim()))
{
MessageBox.Show(messageString, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox.Focus();
return false;
}
else
{
return true;
}
}
刚刚这样打电话:
bool isValidateSuccess = IsValidateTextBoxSuccess(textBoxUsername, "Enter your username") ? IsValidateTextBoxSuccess(textBoxPassword, "Enter your password") :false ;
if(isValidateSuccess)
{
// Then check with the database with entered credential is valid or not
}
else
return;