2013-10-17 105 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。