2016-04-30 65 views
0

它是这样的,我有一个最大值为4的numericUpDown。我想这样做,如果值是1,只有一个按钮出现,如果值是2,出现两个按钮等。我该如何管理在代码中这样做?我正在使用一个计时器,并且在每个tick上它检查numericUpDown的值是否发生变化,并且它是否改变了它的添加按钮,但是如果值减少,我怎么能做相反的事情,删除按钮?例如,如果我具有4的值,并且如果我用1减少,则已经出现了4个按钮,只有一个按钮应该消失。我怎样才能做到这一点 ?计数器增加或减少时立即显示和隐藏按钮?

private void timer1_Tick(object sender, EventArgs e) 
    { 
     if (numericUpDown1.Value == 1) 
     { 
      metroComboBox3.Show(); 
     } 
     else if (numericUpDown1.Value == 2) 
     { 
      metroComboBox4.Show(); 
     } 
    } 
+0

当你说numericUpDown减少了一个和一个按钮消失你的意思是:如果numericUpDown从4减少到3,button4消失或button1消失? –

+0

而不是定时器,使用[NumericUpDown.ValueChanged事件](https://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown.valuechanged(v = vs.110).aspx) 。 –

回答

0

如果你有一个计时器做,那么这是要走的路:

private void timer1_Tick(object sender, EventArgs e) 
{ 
    var buttons = new [] { button1, button2, button3, button4, }; 
    for (var i = 0; i < buttons.Length; i++) 
    { 
     buttons[i].Visible = numericUpDown1.Value - 1 >= i 
    } 
} 

但我会使用numericUpDown1.ValueChanged事件并执行此操作:

private void numericUpDown1_ValueChanged(object sender, EventArgs e) 
{ 
    var buttons = new [] { button1, button2, button3, button4, }; 
    for (var i = 0; i < buttons.Length; i++) 
    { 
     buttons[i].Visible = numericUpDown1.Value - 1 >= i 
    } 
} 
+0

基于这个问题,没有理由使用定时器来检查数字向上/向下的值。我意识到它包含了完整性,但我不想看到年轻的开发人员看到这个答案,并认为使用计时器是一个适当的路径。 –

+0

@MetroSmurf - 我完全同意。我确实试图用“如果你必须”和“但我会用”措辞来传达这个信息。 – Enigmativity

1

只需在设计中双击numericUpDown,就不需要计时器。

你会得到private void numericUpDown1_ValueChanged

Afther你的代码应该是这样的:

private void numericUpDown1_ValueChanged(object sender, EventArgs e) 
     { 
      if (numericUpDown1.Value == 1) 
      { 
       metroComboBox3.Show(); 
      } 
      else if (numericUpDown1.Value == 2) 
      { 
       metroComboBox4.Show(); 
      } 
     }