【问题标题】:C# winform how textbox became null on button click second time?C# winform 如何在第二次单击按钮时文本框变为空?
【发布时间】:2011-01-24 10:13:38
【问题描述】:

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

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

以下测试场景有效:

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

但是,在以下测试场景中,会引发“未设置对象实例的对象引用”异常:

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

我已经放置了断点,它显示特定的文本框为空。我破坏顺序的每个文本框都会发生这种情况。

请指导我哪里不正确以及如何解决它。

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

 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);

        }





    }

【问题讨论】:

    标签: c# winforms .net-3.5 c#-2.0


    【解决方案1】:

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

    txtUnitPrice = null;
    

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

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

    【讨论】:

    • p/s - 当您将 .Text 设置为 null 时,它在内部使用 String.Empty。看起来有点短..
    • 尽管如此。我更喜欢使用 String.Empty,因为通常当我必须重构遗留代码时,我会看到像 txtBox.Text = "" 这样的东西。这很丑陋。
    【解决方案2】:

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

    else
    {
        txtUnitPrice = null;
    }
    

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

    else
    {
        txtUnitPrice.Text = String.Empty;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多