如何在C#Winform中编写这个条件

时间:2014-03-04 07:10:20

标签: c# asp.net .net winforms c#-4.0

我有一个按钮来选择发件人。点击该按钮会显示所有发件人的详细信息,例如发件人ID,国家/地区,名称等。对于接收者也是如此。

现在,如果我选择一个发件人,它会自动填充父表单字段的名称,国家/地区等,同样也是接收者。

现在,我有一个商业条件,如果Sender和Receiver都是UK,那么我需要禁用具有默认值的组合框。有人可以帮我怎么做,因为我觉得在我的情况下,它有点复杂,因为在形式上,有很多字段,我不需要先填写发件人,然后依次填写收件人等。我可以填写任何序列,并且只有在发件人和收件人的详细信息都已填写时,它应立即验证此条件并禁用组合框,如果我将发件人/收件人从英国更改为任何其他国家/地区,则应立即启用组合

我试图这样做,但是,我知道有一些语法错误。请帮助我正确的语法,以及如何检查发件人/收件人的任何变化。我想检查发件人文本框和收件人国家组合框的空状态。

请注意 - 发件人是文本框,收件人是Combobox。

if (!string.IsNullOrEmpty(this.txtSenderCountryCode.Text) &&
    !string.IsNullOrEmpty(this.cbRecipientCountry.Text))
{
    this.txtSenderCountryCode.Text == this.cbRecipientCountry.Text == "United Kingdom" ? this.cmbWeightUnit.Enabled = false : this.cmbWeightUnit.Enabled = true;
}

它向我展示了两个错误:

  
      
  1. 错误1只有赋值,调用,递增,递减和新对象表达式才能用作语句C:\ Project \ Pack \ Page.cs 2739 29包

  2.   
  3. 错误2运算符'=='无法应用于'bool'和'string'类型的操作数C:\ Project \ Pack \ Page.cs 2739 29包

  4.   

3 个答案:

答案 0 :(得分:2)

三元运算符? :不能像语句一样使用,它是一个表达式并返回一个值。它最常用,如

variable = condition ? value_if_true : value_if_false;
SomeMethod(condition ? value_if_true : value_if_false);

这样可以避免编写另一个if语句,同时仍保持代码可读。

所以你想做的是(如果我理解你的话):

if (txtSenderCountryCode.Text == "United Kingdom" &&
    cbRecipientCountry.Text == "United Kingdom")
{
    cmbWeightUnit.Enabled = false;
}
else
{
    cmbWeightUnit.Enabled = true;
}

或者

cmbWeightUnit.Enabled = !(txtSenderCountryCode.Text == "United Kingdom" &&
                          cbRecipientCountry.Text == "United Kingdom");

答案 1 :(得分:1)

if (!string.IsNullOrEmpty(this.txtSenderCountryCode.Text) 
    && !string.IsNullOrEmpty(this.cbRecipientCountry.Text))
{
    this.cmbWeightUnit.Enable = !String.Equals(this.txtSenderCountryCode.Text, "United Kingdom") 
                                && String.Equals( this.cbRecipientCountry.Text, "United Kingdom");
}

答案 2 :(得分:1)

据我所见(逆向工程),您的任务是将cmbWeightUnit.Enabled切换为 true当且仅当发件人收件人国家/地区不是Greate Britain时。如果是你的情况,代码将很简单:

// cmbWeightUnit should be enabled unless both txtSenderCountryCode and cbRecipientCountry 
// are United Kingdom
cmbWeightUnit.Enabled = ! (String.Equals(txtSenderCountryCode.Text, "United Kingdom") &&
                           String.Equals(cbRecipientCountry.Text, "United Kingdom"));

如果您要设置许多参数(不仅仅是一个 cmbWeightUnit),您可以将比较提取到属性:< / p>

  private Boolean IsUnitedKingdom {
    get {
      return String.Equals(txtSenderCountryCode.Text, "United Kingdom") &&
             String.Equals(cbRecipientCountry.Text, "United Kingdom"); 
    }
  }

  ...

  cmbWeightUnit.Enabled = !IsUnitedKingdom;
  myCombobox.Text = IsUnitedKingdom ? "Pound" : "KGS";
  ...
相关问题