2 回答

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
目前尚不清楚您要做什么-但是如果我理解正確-您想跟蹤是否存在錯(cuò)誤,并且僅在沒(méi)有錯(cuò)誤的情況下進(jìn)行保存?您可以使用指示是否有任何錯(cuò)誤的布爾值來(lái)執(zhí)行此操作。此外 - 您的 MessageBox 只有 Ok 按鈕 - 所以使用 if 語(yǔ)句沒(méi)有意義。你的意思是確定取消嗎?
請(qǐng)參閱下面修改后的代碼中的注釋?zhuān)?/p>
private void button1_Click(object sender, EventArgs e)
{
Regex regex1 = new Regex("^[a-zA-Z ]+$");
Regex dat = new Regex("^(0[1-9]|[12][0-9]|3[01])(0[1-9]|1[012])([0-9]{2})[-]([0-9]{5})$");
Regex epasts = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
// Use a boolean to determine whether there is an error
var valid = true;
if (!regex1.IsMatch(textBox1.Text))
{
valid = false;
label5.ForeColor = Color.Red;
label5.Text = "Incorrectly entered name!";
}
else
{
label5.Text = "";
}
if (String.IsNullOrEmpty(textBox1.Text))
{
valid = false;
label5.ForeColor = Color.Red;
label5.Text = "Name wasn't entered!";
}
if (!regex1.IsMatch(textBox2.Text))
{
valid = false;
label6.ForeColor = Color.Red;
label6.Text = "Surname entered incorrectly!";
}
else
{
label6.Text = "";
}
if (String.IsNullOrEmpty(textBox2.Text))
{
valid = false;
label6.ForeColor = Color.Red;
label6.Text = "No surname!";
}
if (!dat.IsMatch(textBox3.Text))
{
valid = false;
label7.ForeColor = Color.Red;
label7.Text = "Incorrect code!";
}
else
{
label7.Text = "";
}
if (String.IsNullOrEmpty(textBox3.Text))
{
valid = false;
label7.ForeColor = Color.Red;
label7.Text = "Not entered!";
}
if (!epasts.IsMatch(textBox4.Text))
{
valid = false;
label8.ForeColor = Color.Red;
label8.Text = "Incorrectly entered email!";
}
else
{
label8.Text = "";
}
if (String.IsNullOrEmpty(textBox4.Text))
{
valid = false;
label8.ForeColor = Color.Red;
label8.Text = "Email not entered!";
}
// Now you can check if there is an error
if (valid)
{
// This doesn't make any sense - because the user can ONLY click ok
//if (MessageBox.Show("Data is being saved", "Data saving", MessageBoxButtons.OK) == DialogResult.OK)
// I think you maybe meant something like this?
if (MessageBox.Show("Data is being saved", "Data saving", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
// And here - I'm assuming you would save the data somewhere and then clear the textboxes?
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
else
{
MessageBox.Show("Please correct the errors and try again");
}
}

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊
在你的方法開(kāi)始時(shí)把這個(gè):
bool valid = true;
if在您發(fā)現(xiàn)輸入錯(cuò)誤的每個(gè)地方都輸入以下內(nèi)容:
valid = false;
然后在方法的最后放這個(gè):
if (valid && MessageBox.Show("Data is being saved", "Data saving", MessageBoxButtons.OK) == DialogResult.OK)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
- 2 回答
- 0 關(guān)注
- 107 瀏覽
添加回答
舉報(bào)