2014-01-11 18 views
0

每當用戶按下上一個空文本字段的退格鍵時,出現以下錯誤消息:防止當用戶按下退格按鈕時文本字段是空的錯誤消息

類型「System.ArgumentOutOfRangeException」的未處理的異常在mscorlib.dll中發生了 。附加信息:StartIndex不能爲 小於零。

如何讓它忽略退格鍵按下,如果文本字段爲空。

private void btnback_Click(object sender, EventArgs e) 
    { 
     if (remainTxt.BackColor == Color.FromArgb(245, 244, 162)) 
     { 
      remainTxt.Text = remainTxt.Text.Remove(remainTxt.Text.Length - 1, 1); 
     } 
     else if (totalTxt.BackColor == Color.FromArgb(245, 244, 162)) 
     { 
      totalTxt.Text = totalTxt.Text.Remove(totalTxt.Text.Length - 1, 1); 
     } 
     else if (paidTxt.BackColor == Color.FromArgb(245, 244, 162)) 
     { 
      paidTxt.Text = paidTxt.Text.Remove(paidTxt.Text.Length - 1, 1); 
     } 
    } 

回答

1

我會抽象出了刪除最後一個字符操作成一個函數,對一個空的文本字段衛士

private void RemoveLast(TextBox tb) { 
    if (tb.Text.Length > 0) { 
    tb.Text = tb.Text.Remove(tb.Text.Length - 1, 1); 
    } 
} 

然後切換事件處理程序使用該功能

private void btnback_Click(object sender, EventArgs e) 
{ 
    if (remainTxt.BackColor == Color.FromArgb(245, 244, 162)) 
    { 
     RemoveLast(remainTxt); 
    } 
    else if (totalTxt.BackColor == Color.FromArgb(245, 244, 162)) 
    { 
     RemoveLast(totalTxt); 
    } 
    else if (paidTxt.BackColor == Color.FromArgb(245, 244, 162)) 
    { 
     RemoveLast(paidTxt); 
    } 
} 
1

你必須檢查,如果文本長度不爲0的Text.Remove功能在您的處理程序的第一個參數得-1作爲第一個參數。這會導致拋出異常,因爲這不是有效的索引。您應該將整個方法正文換成if (remainTxt.Text.Length > 0)區塊

1

聽起來就像您試圖以錯誤的方式解決問題。你遇到的問題是你的代碼沒有檢查是否在之前的文本框是空的你運行一些邏輯。

在嘗試從Length屬性中減去1之前,更改您的代碼以檢查!string.IsNullOrEmpty(remainTxt.Text)(和其他)。由於文本框爲空,因此Length - 1爲-1,確實超出範圍。

相關問題