0

フォームにいくつかのテキストボックスがあります。0.00を自動的に追加するためにleaveイベントのコードを書きました。2つのテキストボックスの値を3番目のテキストボックスに追加するコードを次のように記述しました

try
{
    decimal netVal = 0;
    decimal.TryParse(txtNetValue.Text, out netVal);
    decimal disc2 = 0;
    decimal.TryParse(txtDisc2.Text, out disc2);
    decimal tax1 = 0;
    decimal.TryParse(txtTax1.Text, out tax1);

    decimal tax = netVal - disc2;
    string strtax = ((tax / 100) * tax1).ToString();
    txtTax2.Text = strtax.Substring(0, strtax.IndexOf(".") + 3);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

この場合、新しいボタンをクリックしてすべてのコントロールをクリアすると、例外が発生しIndex and length must refer to a location within the string. Parameter name: lengthます。

4

2 に答える 2

2

Your issue is here:

strtax.Substring(0, strtax.IndexOf(".") + 3);

I don't believe that Substring does what you think it does. The arguments are not "startIndex" and "endIndex" (Beginning and End), they are "startIndex" and "Length" (Beginning and length of substring). Most likely, this confusion is causing you to attempt to get a substring that is larger than the size of the string.

For example, you're saying I want the last 10 characters of "Test". "Test" only has four characters, so trying to get the "last ten" will cause that error.

于 2012-12-15T05:55:24.310 に答える
2

あなたの最終目標は、値をお金としてフォーマットすることです。この場合、便利な Decimal.ToString("C") を使用できます。代わりに必要なフォーマットは他にもたくさんあります。フォーマットの詳細については、このリンクを参照してください

于 2012-12-15T06:13:23.667 に答える