c# - C# 如何将错误附加到 1 个单个消息框中?
问题描述
这是我在 C# 中的当前代码:
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("User Field Is Empty");
return;
}
if (string.IsNullOrEmpty(textBox2.Text))
{
MessageBox.Show("Document Reference Code Field Is Empty");
return;
}
什么是创建数组并附加到数组以显示 1 个 MessageBox 并指出空值的正确方法,而不是拥有多个 MessageBox 并为每个错误消息单击“确定”?
我正在尝试复制它与此 Python 代码相同:
errors = []
if self.nameEntry.get() == '':
errors.append('User')
if self.documentReferenceCodeEntry.get() == '':
errors.append('Document Reference')
if errors:
messagebox.showerror("Error", "Following fields are empty:" +'\n' + '\n'.join(errors))
return('error')
上面的代码是什么,如果该字段为空,则将其附加到errors
数组中,最后将所有错误显示到 1 个消息框中。
这是 Python 代码的输出:
解决方案
使用 List 存储错误,如果列表不为空,则显示 MessageBox
List<string> errors = new List<string>();
if (string.IsNullOrEmpty(textBox1.Text))
{
errors.Add("User");
}
if (string.IsNullOrEmpty(textBox2.Text))
{
errors.Add("Document Reference Code");
}
if(errors.Count > 0)
{
errors.Insert(0, "The following fields are empty:");
string message = string.Join(Environment.NewLine, errors);
MessageBox.Show(message);
}
推荐阅读
- html - 在另一台笔记本电脑中打开网页设计的不同视图
- javascript - Javascript Mouseup / Touchend eventListener 变量未定义
- arangodb - 获取结果集的索引
- c++ - 数组大于 C++ 中的指定大小
- javascript - 我从哪里调用“付款成功”消息?
- regex - 带下划线和正斜杠的 Perl RegEX
- ios - 将图像覆盖到 CGRect swift
- python - 为什么每个循环(据我了解)无法对数组执行操作?
- algorithm - 与其他 n 个顶点距离最小的顶点
- java - 具有连接和动态参数的 JPA Criteria Builder