代码之家  ›  专栏  ›  技术社区  ›  Smiley

文本框事件小问题-C#

  •  0
  • Smiley  · 技术社区  · 15 年前

        private void TextChangeUpdate(object sender, EventArgs e)
        {
            if (this.Text.Trim() != "")
            {
                txtAmountPaid1.Text = (Convert.ToInt32(txtQuantity1.Text) * Convert.ToDecimal(txtUnitPrice1.Text)).ToString();
                txtAmountPaid2.Text = (Convert.ToInt32(txtQuantity2.Text) * Convert.ToDecimal(txtUnitPrice2.Text)).ToString();
                txtAmountPaid3.Text = (Convert.ToInt32(txtQuantity3.Text) * Convert.ToDecimal(txtUnitPrice3.Text)).ToString();
                txtSubtotalProducts.Text = (Convert.ToDecimal(txtAmountPaid1.Text) + Convert.ToDecimal(txtAmountPaid2.Text) + Convert.ToDecimal(txtAmountPaid3.Text)).ToString();
    
                txtSubtotalExpenses.Text = (Convert.ToDecimal(txtWaterBill.Text) + Convert.ToDecimal(txtElectricBill.Text) + Convert.ToDecimal(txtOfficeRent.Text) + Convert.ToDecimal(txtMiscellaneous.Text)).ToString();
    
                txtProductExpenses.Text = txtSubtotalProducts.Text;
                txtOtherExpenses.Text = txtSubtotalExpenses.Text;
                txtTotalExpenses.Text = (Convert.ToDecimal(txtProductExpenses.Text) + Convert.ToDecimal(txtOtherExpenses.Text)).ToString();
            }
        }
    

    现在我的问题来了:

    if (this.Text.Trim() != "")
    

    我需要检查哪个文本框当前正在使用此事件(TextChangeUpdate)。这是因为我需要检查值是否等于“”。然而,“this”关键字似乎不起作用。

    有人帮我吗?:)谢谢。

    8 回复  |  直到 15 年前
        1
  •  0
  •   Klinger    15 年前

    你应该有:

    if (((TextBox)sender).Text.Trim()...
    

    而不是:

    if (this.Text.Trim()
    

    var tb = sender as TextBox;
    if (tb.Text != null && tb.Text.Trim()...
    
        2
  •  2
  •   Wil P    15 年前

    您可以检查处理程序的sender参数,因为它应该是启动要激发的TextChange事件的TextBox。只需将其转换为文本框,然后检查对象属性。

        3
  •  2
  •   prostynick    15 年前

    this sender 但首先你得把它投给 TextBox 所以:

    (sender as TextBox).Text.Trim != ""
    
        4
  •  0
  •   Neil N HLGEM    15 年前

    “this”指的是您所处的窗体,“sender”指的是控件触发的事件

        5
  •  0
  •   Greg D    15 年前

    这正是 sender 对象为。这是对事件来源的引用。在您的例子中,您可以检查发送者对象的属性,一旦您正确地将其强制转换为 TextBox ,来检查你喜欢的东西。

        6
  •  0
  •   Stephen    15 年前

    ((TextBox)sender).Text.Length != 0
    
        7
  •  0
  •   zombiejojo    15 年前

    是啊,克林格说的

    ((Textbox)sender).Text.Trim()
    

    但是您不需要测试null,因为即使您将它设置为null,在检索时它仍然会返回string.empty。

        8
  •  0
  •   SynerCoder    12 年前

    使用 sender as TextBox

    if ((sender as TextBox).Text.Trim() != "")
    {
    
    //code
    
    }