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

VB.NET实现FlowLayoutPanel内同天同时间用户控件重复检测

解决同天同时间重复添加事件的问题

在添加新的UserControl1之前,先遍历对应日期的FlowLayoutPanel中的所有控件,检查是否存在时间重复的事件。如果有重复,弹出错误提示并终止添加流程。

修改后的完整代码如下:

If DomainUpDown1.Text = "Sunday" Then
    ' 获取当前要添加的时间信息(假设Label8/Label9为时间标识)
    Dim targetTime1 As String = Label8.Text
    Dim targetTime2 As String = Label9.Text

    ' 检查FlowLayoutPanel1中是否已有重复时间的事件
    Dim isDuplicate As Boolean = False
    For Each ctrl As Control In FlowLayoutPanel1.Controls
        ' 仅检查自定义的UserControl1控件
        If TypeOf ctrl Is UserControl1 Then
            Dim existingUC As UserControl1 = DirectCast(ctrl, UserControl1)
            ' 对比时间信息判断是否重复
            If existingUC.Label8.Text = targetTime1 AndAlso existingUC.Label9.Text = targetTime2 Then
                isDuplicate = True
                Exit For
            End If
        End If
    Next

    If isDuplicate Then
        ' 弹出重复提示
        MessageBox.Show("该时间段已有事件,无法重复添加!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
        ' 原有添加控件逻辑
        Dim I As New UserControl1
        I.Name = "test:" & _index
        I.Label8.Text = Label8.Text
        I.Label9.Text = Label9.Text
        I.Label10.Text = Label10.Text
        
        Select Case Panel18.BackColor
            Case Color.PowderBlue
                I.BackColor = Color.PowderBlue
            Case Color.MistyRose
                I.BackColor = Color.MistyRose
            Case Color.NavajoWhite
                I.BackColor = Color.NavajoWhite
            Case Color.DarkSeaGreen
                I.BackColor = Color.DarkSeaGreen
        End Select
        
        FlowLayoutPanel1.Controls.Add(I)
        _index += 1
    End If
End If

关键说明

  • 遍历控件时通过TypeOf过滤类型,确保只检查自定义的UserControl1,避免其他控件干扰判断。
  • 若你的时间是标准日期格式,建议将Label文本转换为DateTime类型再对比,可避免文本格式差异导致的误判(比如"9:00"和"09:00"文本不同但时间相同的情况)。
  • 用Select Case替代原有的多分支ElseIf,代码更简洁易维护。

内容的提问来源于stack exchange,提问作者H.S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:05:45