【问题标题】:validate text box - comparing two text box values验证文本框 - 比较两个文本框值
【发布时间】:2019-05-13 10:22:25
【问题描述】:

当我在TxtAdvance 文本框中输入一个值时,如果它高于TxtAssessedVal 框中的值,程序应该会显示错误消息。

 private void TxtAdvance_Validating(object sender, System.ComponentModel.CancelEventArgs e)
 {
       if (float.Parse(TxtAssessedVal.Text) <= float.Parse(TxtAdvance.Text)) 
       {                               
             MessageBox.Show("Advance value shold be less than Assessed value .!", 
                             "Error", 
                              MessageBoxButtons.OK, 
                              MessageBoxIcon.Error);

             TxtAdvance.Focus();
             return;
       }
 }

但是当我输入 90000 的“高级”值和 89600 的“评估”值时,它没有显示错误。

【问题讨论】:

  • 似乎有什么问题?
  • 好像没问题。。怎么了?
  • 好的。发生了什么而不是你预期的?你做了什么调试?你在每个框中输入了什么值来测试它?您不能在不告诉我们问题所在的情况下将一些代码转储给我们,我们无法神奇地猜出您想问什么
  • 您似乎正在检查TxtAdvance 是否等于或小于TxtAssessedVal 不大于
  • 当我输入 90000 作为预付价值和 89600 作为评估价值时,它没有给出错误信息

标签: c# winforms validation comparison-operators


【解决方案1】:

9000089600 大,因此您所写内容的预期行为是它不应该显示错误。您的代码将是这样的:if (89600 &gt;= 90000) { MessageBox.Show //etc....。换句话说,它的意思是“如果 89600 大于或等于 9000 则显示错误”。显然,89600 不大于或等于 9000,因此不会显示该消息。

我认为您只是将“大于”与“小于”混淆了。尝试使用&lt;= 而不是&gt;=

if (float.Parse(TxtAssessedVal.Text) <= float.Parse(TxtAdvance.Text))

或者,如果您想让代码读起来更符合您的要求,那么请交换文本框:

if (float.Parse(TxtAdvance.Text) >= float.Parse(TxtAssessedVal.Text))

附:您的要求还说“如果更高”,但没有提到“或等于”。因此,您可能还需要删除 =,因为在这种情况下,如果两个值都是(例如)90000,则会显示错误。所以实际上也许代码应该是:

if (float.Parse(TxtAdvance.Text) > float.Parse(TxtAssessedVal.Text))

改为。


附言我建议您阅读文档https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/comparison-operators 并确保您清楚地理解每个运算符符号的含义。

【讨论】:

  • 我改变了我的代码 if (float.Parse(TxtAdvance.Text) > float.Parse(TxtAssessedVal.Text)) 像这样,但它没有闪烁
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 1970-01-01
  • 2021-04-12
  • 2015-09-24
相关资源
最近更新 更多