2013-10-17 104 views
0

有沒有什麼辦法來限制組合框的值爲'0',其中我的音量值除以目標值,因爲我的目標值是組合框,並給我一個錯誤除以零。我試過這個,但沒有祝你好運。限制組合框輸入零用戶

private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) 
     { 
      if (!char.IsNumber(e.KeyChar) && (e.KeyChar != '0')) 
      { 
       e.Handled = true; 
      } 

     } 
+0

你只需要輸入爲零?或阻止用戶輸入零點? –

+0

防止用戶輸入零點 – preethi

+0

如果用戶輸入'10'會怎麼樣?你需要允許還是不允許? –

回答

5

簡單的方法是處理TextChanged事件並將其重置爲以前的值。 或按照建議在註釋中不允許用戶輸入值只是讓他從列表中選擇(DropDownList樣式)。

private string previousText = string.Empty; 
private void comboBox1_TextChanged(object sender, EventArgs e) 
{ 
    if (comboBox1.Text == "0") 
    { 
     comboBox1.Text = previousText; 
    } 

    previousText = comboBox1.Text; 
} 

我提出這個解決方案,因爲處理關鍵事件是一場噩夢,你需要檢查以前的值,複製+粘貼菜單,按Ctrl + V快捷鍵等。

+0

+1將事件更改爲_TextChanged_並使用_previousText_捕獲塊覆蓋(其他回答中的_KeyPress_建議中的「!IsNumber」將阻止啓動的刪除鍵)。 – n4m16

+0

@Nick不僅刪除鍵,退格鍵,選擇全部並用一些字符等替換等等等等,有太多的問題要覆蓋這種方法,這會稍後給你帶來麻煩。這不會失敗,隨時AFAIK :) –

0

你可以試試這個:

private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (!char.IsNumber(e.KeyChar) 
      || (e.KeyChar == '0' 
       && this.comboBox1.Text.Length == 0)) 
     { 
      e.Handled = true; 
     } 
    } 
0

如果您確實希望使用此事件來阻止零的條目,然後考慮以下幾點:

private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsNumber(e.KeyChar)) 
    { 
     e.Handled = true; 
     return; 
    } 

    if (e.KeyChar == '0') 
    { 
     if (comboBox1.Text == "") 
     { 
      e.Handled = true; 
      return; 
     } 
     if (int.Parse(comboBox1.Text) == 0) 
     { 
      e.Handled = true; 
      return; 
     } 
    } 
} 

該代碼可能會有點整理,但希望它顯示了一個阻止前導零的簡單方法 - 我認爲這是你以後的樣子。當然,一旦你擁有了正確的邏輯,這些條款都可以組合成一個IF。