c# - 如果所有文本框都成功完成,我如何显示此消息框
问题描述
我是 C# 的初学者,我自己编写了一个程序。它检查是否所有文本框都正确填充,然后在按下保存按钮时应该显示消息框,但如果所有文本框都不正确,则不应显示它
这是消息框代码:
if (MessageBox.Show("Data is being saved", "Data saving", MessageBoxButtons.OK) == DialogResult.OK)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
这是完整的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _5_prakt
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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})+)$");
if (!regex1.IsMatch(textBox1.Text))
{
label5.ForeColor = Color.Red;
label5.Text = "Incorrectly entered name!";
}
else
{
label5.Text = "";
}
if (String.IsNullOrEmpty(textBox1.Text))
{
label5.ForeColor = Color.Red;
label5.Text = "Name wasn't entered!";
}
if (!regex1.IsMatch(textBox2.Text))
{
label6.ForeColor = Color.Red;
label6.Text = "Surname entered incorrectly!";
}
else
{
label6.Text = "";
}
if (String.IsNullOrEmpty(textBox2.Text))
{
label6.ForeColor = Color.Red;
label6.Text = "No surname!";
}
if (!dat.IsMatch(textBox3.Text))
{
label7.ForeColor = Color.Red;
label7.Text = "Incorrect code!";
}
else
{
label7.Text = "";
}
if (String.IsNullOrEmpty(textBox3.Text))
{
label7.ForeColor = Color.Red;
label7.Text = "Not entered!";
}
if (!epasts.IsMatch(textBox4.Text))
{
label8.ForeColor = Color.Red;
label8.Text = "Incorrectly entered email!";
}
else
{
label8.Text = "";
}
if (String.IsNullOrEmpty(textBox4.Text))
{
label8.ForeColor = Color.Red;
label8.Text = "Email not entered!";
}
if (MessageBox.Show("Data is being saved", "Data saving", MessageBoxButtons.OK) == DialogResult.OK)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
}
}
解决方案
在你的方法开始时把这个:
bool valid = true;
if
在您发现输入错误的每个地方都输入以下内容:
valid = false;
然后在方法的最后放这个:
if (valid && MessageBox.Show("Data is being saved", "Data saving", MessageBoxButtons.OK) == DialogResult.OK)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
推荐阅读
- watchos - 如何使用 Apple Watch 的 os_log 访问过去一天的日志?
- android - 如何在android中通过HTTP POST发送二维字符串数组
- java - 这是java中的东西吗?
- javascript - jQuery的切换方法
- ios - Swift - 如何使用 UISearchController 过滤多个关键字
- excel - 如何根据唯一票汇总借记费条目#
- reactjs - Partialview/View 组件 VS Reactjs 组件
- python - 具有共享权重的 Keras Dense 模型
- html - 移动视图中的表格从页面上脱落
- react-native - stickyHeaderIndices 与 FlatList 数据索引不正确匹配