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

VB中如何验证空TextBox、ComboBox及日期控件并实现数据保存

解决销售数据窗体的字段验证与保存触发问题

我开发了一个将销售数据存入数据库的窗体,需求为:

  • 若用户未填全所有字段,需高亮空控件(目前部分ComboBox和日期控件未被正确高亮)
  • 若所有字段均非空,则执行数据保存操作

已编写数据保存代码,但不知如何构建判断逻辑来实现非空时触发保存的功能。


现有代码问题分析

  1. ComboBox判断冗余且不严谨:重复判断combo.Text = "",未覆盖ComboBox未选中任何项的场景(SelectedIndex = -1)
  2. 日期控件类型判断错误:TypeOf Dt Is Date是错误的,日期控件类型应为DateTimePicker,且其Text不会为空,需判断是否选择了有效日期
  3. 无全局验证状态跟踪:仅高亮空控件,但未记录是否存在未填项,无法触发后续保存逻辑
  4. SQL注入风险:原保存代码直接拼接SQL字符串,存在安全隐患

解决方案

步骤1:修正字段验证逻辑,添加状态跟踪

修改btnAdd_Click方法,通过isValid变量跟踪所有字段的填写状态,同时正确处理各类控件的验证:

Public Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    Dim isValid As Boolean = True
    ' 重置所有控件背景色,清除之前的高亮残留
    For Each ctrl In Panel1.Controls
        ctrl.BackColor = SystemColors.Window
    Next

    ' 验证TextBox
    For Each txt In Panel1.Controls.OfType(Of TextBox)()
        If String.IsNullOrWhiteSpace(txt.Text) Then
            txt.BackColor = Color.Yellow
            txt.Focus()
            isValid = False
        End If
    Next

    ' 验证ComboBox:未选中项或文本为空均视为未填写
    For Each combo In Panel1.Controls.OfType(Of ComboBox)()
        If combo.SelectedIndex = -1 OrElse String.IsNullOrWhiteSpace(combo.Text) Then
            combo.BackColor = Color.Yellow
            combo.Focus()
            isValid = False
        End If
    Next

    ' 验证DateTimePicker:判断是否为默认初始日期(可根据需求调整条件)
    For Each dtPicker In Panel1.Controls.OfType(Of DateTimePicker)()
        If dtPicker.Value = dtPicker.MinDate Then
            dtPicker.BackColor = Color.Yellow
            dtPicker.Focus()
            isValid = False
        End If
    Next

    ' 所有字段验证通过则执行保存
    If isValid Then
        save_data()
    Else
        MessageBox.Show("请填写所有必填字段!")
    End If
End Sub

步骤2:修复保存代码的SQL注入风险

将直接拼接SQL的方式改为参数化查询,同时修正数据操作的错误用法:

Public Sub save_data()
    MysqlConn = New MySqlConnection
    MysqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=golden_star"

    Try
        If MessageBox.Show("Do you want to save the changes?", "Save Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
            MysqlConn.Open()
            ' 参数化SQL语句
            Dim Query As String = "INSERT INTO golden_star.sales 
                (date, brand, size, selling_unit_price, cost_unit_price, quantity, cost_of_goods, profit, total_cost_price) 
                VALUES (@Date, @Brand, @Size, @SellingPrice, @CostPrice, @Quantity, @CostOfGoods, @Profit, @TotalCost)"

            Using cmd As New MySqlCommand(Query, MysqlConn)
                ' 添加参数(替换为你的实际控件名)
                cmd.Parameters.AddWithValue("@Date", DateTimePicker1.Value)
                cmd.Parameters.AddWithValue("@Brand", ComboBox1.Text)
                cmd.Parameters.AddWithValue("@Size", ComboBox2.Text)
                cmd.Parameters.AddWithValue("@SellingPrice", txtSelling.Text)
                cmd.Parameters.AddWithValue("@CostPrice", txtCostPrice.Text)
                cmd.Parameters.AddWithValue("@Quantity", ComboBox3.Text)
                cmd.Parameters.AddWithValue("@CostOfGoods", txtTotalSell.Text)
                cmd.Parameters.AddWithValue("@Profit", txtProfit.Text)
                cmd.Parameters.AddWithValue("@TotalCost", txtCp.Text)

                ' 插入操作使用ExecuteNonQuery而非ExecuteReader
                cmd.ExecuteNonQuery()
                MessageBox.Show("Daily Sales Entered Successfully")
            End Using
        End If
    Catch ex As MySqlException
        MessageBox.Show(ex.Message)
    Finally
        ' 确保连接关闭
        If MysqlConn.State = ConnectionState.Open Then
            MysqlConn.Close()
        End If
        MysqlConn.Dispose()
    End Try
End Sub

关键说明

  • isValid变量全局跟踪验证状态,只要有一个控件未通过验证,就阻止保存操作
  • 使用OfType(Of T)()简化控件遍历,无需额外类型判断
  • DateTimePicker的验证条件可根据需求调整(比如允许使用当前日期作为默认值)
  • 参数化查询彻底避免SQL注入,同时解决特殊字符、日期格式等问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:50:21