Is this the correct way to set value of textbox to zero when it's null? Is there any way I can improve the calculation that I am doing?
private void TB_PAID_CASH_TextChanged(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(TB_TOTAL_INV.Text) && !string.IsNullOrEmpty(TB_PAID_CASH.Text) && string.IsNullOrEmpty(TB_Discount.Text))
{
int Discount;
int.TryParse(TB_Discount.Text, out Discount);
TB_REMAINDER.Text = (Convert.ToInt32(TB_PAID_CASH.Text) - Convert.ToInt32(TB_TOTAL_INV.Text) - Discount).ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
1 Answer 1
You are mixing various things here. For some values you use the try/catch
and for others the TryParse
. I think you should stick to one of them.
What I also don't understand is why you are checking whether this is true string.IsNullOrEmpty(TB_Discount.Text)
and then try to parse it anyway int.TryParse(TB_Discount.Text)
?
Here is what you can do:
Create a property for each value:
public int TotalInv
{
get
{
int totalInv;
return int.TryParse(TB_TOTAL_INV.Text, out totalInv) ? totalInv : 0;
}
}
public int PaidCash
{
get
{
int paidCash;
return int.TryParse(TB_PAID_CASH.Text, out paidCash) ? paidCash : 0;
}
}
public int Discount
{
get
{
int discount;
return int.TryParse(TB_Discount.Text, out discount) ? discount : 0;
}
}
For the reminder too:
public int Reminder
{
get
{
return PaidCash - TotalInv - Discount;
}
}
Then when the text changes you can update the text box with only one line:
private void TB_PAID_CASH_TextChanged(object sender, EventArgs e)
{
if(PaidCash < TotalInv)
{
// todo: show message...
}
TB_REMAINDER.Text = Reminder.ToString();
}
-
\$\begingroup\$ Thanks alot for help I was not know about it.. I read about But can I check the property ? for example if PaidCash property are less than TotalInv property I want to show the user a message box to notify him ? \$\endgroup\$samer– samer2016年07月26日 16:44:25 +00:00Commented Jul 26, 2016 at 16:44
-
\$\begingroup\$ @samer sure, you can, I edited the code. See the
if
in the last example. \$\endgroup\$t3chb0t– t3chb0t2016年07月26日 16:49:52 +00:00Commented Jul 26, 2016 at 16:49
TextBox
rather than aNumericUpDown
control for this? \$\endgroup\$