开发者

TextBox Event Small Problem - C#

I have a small problem which I'm having a hard time troubleshooting. I just wanna hear some inputs from you guys. I have like maybe 8 textboxes which all uses the same TextChange Event shown below:

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

            txtSubt开发者_如何学JAVAotalExpenses.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();
        }
    }

Now my problem comes in the line:

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

I need to check which textbox is currently using this Event (TextChangeUpdate). This is because I need to check if the value is equal to "". However, the 'this' keyword doesn't seem to do the job.

Anybody help me please? :) thanks.


You can check the sender param to the handler as it should be the TextBox that initiated the TextChange event to be fired. Just cast it as a TextBox and then inspect the objects properties.


this is probably your form. You need to use sender but first you need to cast it to TextBox so:

(sender as TextBox).Text.Trim != ""


You should have:

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

instead of:

if (this.Text.Trim()

You should probably also test fo Text = null.

var tb = sender as TextBox;
if (tb.Text != null && tb.Text.Trim()...


"this" refers to the Form you are in, "sender" is what control fired the event


That is exactly what the sender object is for. This is a reference to the source of the event. In your case, you could examine the sender object's properties, once you've properly cast it to a TextBox, to examine whatever you like.


use sender

((TextBox)sender).Text.Length != 0


yeah, what Klinger said

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

except you shouldn't need to test for null, since even if you set it to null, on retrieval it will return string.empty anyway.

[note that (sender as Textbox) is VB.net format]


Use sender as TextBox and grab the text.

Example:

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

//code

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜