我正在構建一個將分數轉換爲百分比的應用程序。我希望如此,如果我編輯分數中的文本,它會刷新並重新計算百分比。此代碼爲什麼會導致ArgumentOutOfRangeException?
當我測試它時,我第一次編輯它沒有錯誤的分數,並且工作正常,但是第二次我改變了分數中的錯誤。我得到這個錯誤
類型System.ArgumentOutOfRangeException未處理的異常出現在mscorlib.dll
我能做些什麼來解決這個問題?
我對C#相當陌生,所以如果可能的話,儘量貶低它。
其他信息:索引和長度必須引用位置的字符串中的「
這裏是我到目前爲止:
private void fractionNumerator_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsNumber(e.KeyChar) || ((e.KeyChar) == Convert.ToChar(Keys.Back))))
{
e.Handled = true;
}
else
{
if (!((fractionNumerator.Text == "") && (fractionDenominator.Text == "")))
{
if ((e.KeyChar == Convert.ToChar(Keys.Back)))
{
string numer = (fractionNumerator.Text.Substring(0, (fractionNumerator.Text.Length) - 1));
string denom = (fractionDenominator.Text);
outputPercentage.Text = (((((Convert.ToDouble(numer)/Convert.ToDouble(denom)) * 100).ToString()).Substring(0, 6)) + "%");
}
else
{
string numer = ((fractionNumerator.Text) + e.KeyChar.ToString());
string denom = (fractionDenominator.Text);
outputPercentage.Text = (((Convert.ToDouble(numer)/Convert.ToDouble(denom)*100).ToString()).Substring(0, 6));
}
}
}
}
private void fractionDenominator_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsNumber(e.KeyChar) || ((e.KeyChar) == Convert.ToChar(Keys.Back))))
{
e.Handled = true;
}
else
{
if (!((fractionNumerator.Text == "") && (fractionDenominator.Text == "")))
{
if ((e.KeyChar == Convert.ToChar(Keys.Back)))
{
string denom = (fractionDenominator.Text.Substring(0, (fractionDenominator.Text.Length) - 1));
string numer = (fractionNumerator.Text);
outputPercentage.Text = (((((Convert.ToDouble(numer)/Convert.ToDouble(denom)) * 100).ToString()).Substring(0, 6)) + "%");
}
else
{
string denom = ((fractionDenominator.Text) + e.KeyChar.ToString());
string numer = (fractionNumerator.Text);
outputPercentage.Text = (((Convert.ToDouble(numer)/Convert.ToDouble(denom) * 100).ToString()).Substring(0, 6));
}
}
}
}
你在哪條線上發生錯誤? –
我猜它是'Substring(0,6))',它以某種方式被調用的字符串少於6個字符。 –
這是'Substring'調用之一。停止使用Substring格式化雙輸出。使用格式說明符:http://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx –