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

如何用C#方法验证WPF表单空字段及修复验证逻辑失效问题

WPF ComboBox验证逻辑失效问题

已完成WPF前端界面开发,需编写C#后端逻辑对**Compartment(ComboBox)和Purpose(ComboBox)**进行验证:当选中指定Compartment且Purpose选择为「Full(满载)」时,必须在用户点击保存票据按钮前完成校验。目前存在两个问题:

  • 验证逻辑未正确生效
  • 调试时无法命中对应代码行

WPF UI代码

<Label x:Name="lblPurpose" Content="Purpose:" HorizontalAlignment="Left" Margin="12,141,0,0" VerticalAlignment="Top" Width="93" HorizontalContentAlignment="Right" Background="#FFE3E3E3" FontWeight="SemiBold" BorderThickness="1" BorderBrush="#FFBEBEBE"/>
<ComboBox x:Name="cbxPurpose" HorizontalAlignment="Left" Margin="110,142,0,0" VerticalAlignment="Top" Width="119" Height="27"/>
<Label x:Name="lblCompartment" Content="Compartment:" HorizontalAlignment="Left" Margin="12,171,0,0" VerticalAlignment="Top" Width="93" HorizontalContentAlignment="Right" Background="#FFE3E3E3" FontWeight="SemiBold" BorderThickness="1" BorderBrush="#FFBEBEBE"/>
<ComboBox x:Name="cbxCompartment" IsEnabled="True" IsEditable="True" HorizontalAlignment="Left" Margin="110,170,0,0" VerticalAlignment="Top" Width="119" Height="26"/>

后端按钮点击事件代码

private void btnSaveReturn_Click(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrEmpty(txtTicketNu.Text))
    {
        MessageBox.Show("Please select a ticket");
        return;
    }

    if (chkFarmName.IsChecked == true)
    {
        var ticket = Managers.WeighbridgeTicketManager.GetWeighBridgeTicketPK(txtTicketNu.Text);
        ticket.Customer = cbxCustomer.Text;
        ticket.Product = cbxProduct.Text;
        ticket.ReplacementTopSeal = txtRTopSeal.Text;
        ticket.ReplacementBottomSeal = txtRBottomSeal.Text;

        Managers.WeighbridgeTicketManager.UpdateTripsheetCustomer(ticket);
        presenter.PopulateGrid(txtTripsheetNo.Text);
        MessageBox.Show("Ticket " + TicketNumber + " updated successfully.", "Ticket Update");
        ClearFields();

    }
    else
    {
        if (string.IsNullOrEmpty(txtReturnWeight.Text))
        {
            MessageBox.Show("Please enter compartment weight");
            return;
        }
        if (cbxPurpose.SelectedIndex == 0)
        {
            MessageBox.Show("Please select a purpose");
            return;
        }

        if (cbxCompartment.SelectedItem != null && cbxCompartment.SelectedItem.ToString() == "truck-empty")
        {
            if (string.IsNullOrEmpty(txtRTopSeal.Text))
            {
                MessageBox.Show("TopSeal cannot be empty when truck is empty", "Validation Error");
                txtRTopSeal.Focus();
                return;
            }
        }

        ReturnDelivery retDelivery = new ReturnDelivery();
        retDelivery.Comment = txtComment.Text;
        retDelivery.Customer = cbxCustomer.Text;
        retDelivery.Product = cbxProduct.Text;
        retDelivery.Productweight = Convert.ToInt32(txtReturnWeight.Text);
        retDelivery.Purpose = Convert.ToInt32(cbxPurpose.SelectedValue);
        retDelivery.Ticket = Convert.ToInt32(txtTicketNu.Text);
        retDelivery.Trip = Convert.ToInt32(txtTripsheetNo.Text);
        var tickets = Managers.ReturnDeliveryManager.InsertReturnDelivery(retDelivery);
        ClearFields();
        MessageBox.Show("Return has been successfully saved");
       
    }
}

待生效的验证逻辑代码

if (cbxCompartment.SelectedValue != null &&
    cbxPurpose.SelectedValue != null &&
    cbxCompartment.SelectedItem.ToString().ToLower() == "truck-empty" &&
    cbxPurpose.SelectedValue.ToString() == "Leaving-Finished Product")
{
    // 检查TopSeal是否为空
    if (string.IsNullOrEmpty(txtTopSeal.Text))
    {
        MessageBox.Show("TopSeal cannot be empty when the truck is empty and the purpose is Leaving - Finished Product", "Validation Error");
        txtTopSeal.Focus();
        return;
    }

    // 检查BottomSeal是否为空
    if (string.IsNullOrEmpty(txtBottomSeal.Text))
    {
        MessageBox.Show("BottomSeal cannot be empty when the truck is empty and the purpose is Leaving - Finished Product", "Validation Error");
        txtBottomSeal.Focus();
        return;
    }
}

问题排查与修复方案

1. 验证逻辑未生效的核心原因

待生效的验证代码未被添加到按钮点击事件的执行流程中,导致永远不会被触发。需要将这段代码插入到btnSaveReturn_Click事件的合适位置。

2. 调试无法命中代码的解决方式

  • 确保待生效代码已被正确放入btnSaveReturn_Click事件内(建议放在else分支的基础验证之后、数据插入之前)
  • 确认项目处于Debug模式(Release模式会优化代码,导致断点无法命中)
  • 清理解决方案并重新生成,避免旧代码缓存影响

3. 修正后的完整按钮点击事件代码

private void btnSaveReturn_Click(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrEmpty(txtTicketNu.Text))
    {
        MessageBox.Show("请选择票据");
        return;
    }

    if (chkFarmName.IsChecked == true)
    {
        var ticket = Managers.WeighbridgeTicketManager.GetWeighBridgeTicketPK(txtTicketNu.Text);
        ticket.Customer = cbxCustomer.Text;
        ticket.Product = cbxProduct.Text;
        ticket.ReplacementTopSeal = txtRTopSeal.Text;
        ticket.ReplacementBottomSeal = txtRBottomSeal.Text;

        Managers.WeighbridgeTicketManager.UpdateTripsheetCustomer(ticket);
        presenter.PopulateGrid(txtTripsheetNo.Text);
        MessageBox.Show("票据 " + TicketNumber + " 更新成功。", "票据更新");
        ClearFields();

    }
    else
    {
        if (string.IsNullOrEmpty(txtReturnWeight.Text))
        {
            MessageBox.Show("请输入车厢重量");
            return;
        }
        if (cbxPurpose.SelectedIndex == 0)
        {
            MessageBox.Show("请选择用途");
            return;
        }

        if (cbxCompartment.SelectedItem != null && cbxCompartment.SelectedItem.ToString() == "truck-empty")
        {
            if (string.IsNullOrEmpty(txtRTopSeal.Text))
            {
                MessageBox.Show("空车时TopSeal不能为空", "验证错误");
                txtRTopSeal.Focus();
                return;
            }
        }

        // 插入待生效的验证逻辑
        if (cbxCompartment.SelectedValue != null &&
            cbxPurpose.SelectedValue != null &&
            cbxCompartment.SelectedItem.ToString().ToLower() == "truck-empty" &&
            cbxPurpose.SelectedValue.ToString() == "Leaving-Finished Product")
        {
            if (string.IsNullOrEmpty(txtTopSeal.Text))
            {
                MessageBox.Show("空车且用途为「运出成品」时,TopSeal不能为空", "验证错误");
                txtTopSeal.Focus();
                return;
            }

            if (string.IsNullOrEmpty(txtBottomSeal.Text))
            {
                MessageBox.Show("空车且用途为「运出成品」时,BottomSeal不能为空", "验证错误");
                txtBottomSeal.Focus();
                return;
            }
        }

        ReturnDelivery retDelivery = new ReturnDelivery();
        retDelivery.Comment = txtComment.Text;
        retDelivery.Customer = cbxCustomer.Text;
        retDelivery.Product = cbxProduct.Text;
        retDelivery.Productweight = Convert.ToInt32(txtReturnWeight.Text);
        retDelivery.Purpose = Convert.ToInt32(cbxPurpose.SelectedValue);
        retDelivery.Ticket = Convert.ToInt32(txtTicketNu.Text);
        retDelivery.Trip = Convert.ToInt32(txtTripsheetNo.Text);
        var tickets = Managers.ReturnDeliveryManager.InsertReturnDelivery(retDelivery);
        ClearFields();
        MessageBox.Show("退货已成功保存");
       
    }
}

额外优化建议

  • 避免直接使用字符串硬编码(如"truck-empty"、"Leaving-Finished Product"),改用枚举类型,减少拼写错误风险
  • 对Convert.ToInt32添加异常捕获,防止输入非数字时程序崩溃
  • 统一提示信息的中文表述,提升用户体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:02:03