You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在foreach循环中排除DateTimePicker控件?

解决表单控件空值验证及排除DateTimePicker的问题

兄弟,我帮你捋捋这个问题哈,首先你原来的代码里有两个小问题需要修正,然后再搞定排除DateTimePicker的需求:

1. 先修正空值判断的错误逻辑

你原来写的if (control.Text.Contains(null))是不对的——Contains方法不能传null参数,而且判断控件文本是否为空/空白,应该用string.IsNullOrWhiteSpace(control.Text),这个方法能同时检查空字符串、null和全空白的情况,更准确。

2. 排除DateTimePicker控件

要跳过DateTimePicker很简单,在循环里先判断当前控件的类型,如果是DateTimePicker,直接用continue跳过本次循环就行。

修改后的完整代码

List<string> emptycontrols = new List<string>();
foreach (Control control in Mainform.V_Datafield.Controls)
{
    // 跳过DateTimePicker控件
    if (control is DateTimePicker)
        continue;
    
    // 正确判断文本是否为空/空白
    if (string.IsNullOrWhiteSpace(control.Text))
    {
        emptycontrols.Add(control.Name);
    }
}

if (emptycontrols.Count > 0)
{
    // 把空控件列表转成逗号分隔的字符串,不然直接ToString会显示类型名
    MessageBox.Show($"Empty fields detected: {string.Join(", ", emptycontrols)}");
}

另外补充一下:你说DateTimePicker永远不为空是对的,因为它的Text属性默认会显示当前系统日期,哪怕没手动选择,也不会是空值,所以确实需要把它排除在验证逻辑外。

内容的提问来源于stack exchange,提问作者JMC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:50:04