繁体   English   中英

C#winform第二次按钮点击时文本框如何变为空?

[英]C# winform how textbox became null on button click second time?

在一个表单中我有组Box,其中包含带有4个选项卡的选项卡控件。

在第二个选项卡中,我有一些文本框,在保存数据之前,我需要验证在这些textbx中输入的输入。 请注意我的保存按钮位于最后一个标签中。

以下测试方案有效:

  • 第一个文本框中的输入无效
  • 第二个文本框中的输入无效
  • 点击按钮

但是,在以下测试方案中,抛出了“未设置为对象实例的对象引用”异常:

  • 第一个文本框中的输入无效
  • 点击按钮
  • 第二个文本框中的输入无效
  • 点击按钮

我已经设置了断点,它显示特定的文本框为空。 它发生在我打破订单的每个文本框中。

请指导我不正确的地方以及我如何解决它。

下面是我按下按钮时运行的代码。

 private void btnOrderSave_Click(object sender, EventArgs e)
    {
        SaveOrder();

    }

    private void SaveOrder()
    {
        try
        {
            decimal? _marketRate, _bankcharges, _portcharges, _handlingcharges, _othercharges, _taxratio, _profitratio;

            if (!String.IsNullOrEmpty(txtUnitPrice.Text))
            {

                if (valCtr.IsDecimal(txtUnitPrice.Text))
                {
                    _marketRate = Convert.ToDecimal(txtUnitPrice.Text);
                }
                else
                {
                    ErrorMessage("Rate is invalid");                        
                    return;
                }
            }
            else
            {
                txtUnitPrice = null;
            }
            if (!String.IsNullOrEmpty(txtProfitRatio.Text))
            {
                if (valCtr.IsDecimal(txtProfitRatio.Text))
                {
                    _marketRate = Convert.ToDecimal(txtProfitRatio.Text);
                }
                else
                {
                    ErrorMessage("Profit ratio is invalid");                        
                    return;
                }
            }
            else
            {
                txtProfitRatio = null;
            }



        }

        catch (Exception ex)
        {
            AlertMessage(ex.InnerException + " :" + ex.Message + " : " + ex.StackTrace + " : " + ex.Source);

        }





    }

您确定要将文本框本身设置为null而不是.Text或其他成员吗?

txtUnitPrice = null;

称之为预感,但这些会更好吗?

            txtUnitPrice.Text = null;
....
            txtProfitRatio.Text = null;

出现此问题的原因是您将文本框设置为NULL值。

else
{
    txtUnitPrice = null;
}

您应该将Text属性设置为String.Empty,如下所示:

else
{
    txtUnitPrice.Text = String.Empty;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM