带有自动“加/减”功能的C#Numericupdown

时间:2012-07-14 22:28:23

标签: c# winforms

我有NumericUpDown控件,我希望单独文本框中的值减少或增加,具体取决于用户输入的输入(向上或向下)

我用什么事件或代码来完成此任务? 我试过这个,但在运行时遇到错误

  

“无法将'System.Windows.Forms.NumericUpDown'类型的对象强制转换为'System.IConvertible'。

  int UpDownNum;
  int NumBank;
  int TV = 0
  private void UpDown1_MouseUp(object sender, MouseEventArgs e)
    {
        UpDownNum = (Convert.ToInt32(UpDown1));
        NumBank = (Convert.ToInt32(NumTextbox.Text));

        TV = NumBank - UpDownNum;
        NumTextbox.Text = (Convert.ToString(TV));

我做错了事吗?还是其他问题?

2 个答案:

答案 0 :(得分:0)

异常是通过将NumericUpdown控件转换为整数引起的。这不起作用。您需要使用NumericUpdown.Value属性。

我认为这是您正在寻找的ValueChanged事件:

private decimal oldValue = 0;

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    NumericUpDown UpDown1 = (NumericUpDown)sender;
    decimal diff = UpDown1.Value - oldValue;
    oldValue = UpDown1.Value;
    int numBank = int.Parse(NumTextBox.Text);
    decimal newValue = numBank + diff;
    NumTextBox.Text = newValue.ToString();
}

修改

我知道的唯一方法是获取NumericUpDown值的旧值和新值之间的区别是手动保存旧值(例如在成员变量中)并在您之后在ValueChanged中更改它我们计算了差异(参见上面的编辑代码)。

答案 1 :(得分:0)

您必须抓住NumericUpDown.ValueChanged事件,并获取NumericUpDown.Value属性:

private void NumericUpDown1ValueChanged(object sender, EventArgs e)
{
    var num = ((NumericUpDown) sender).Value;
    newTextBox.Text = num.ToString();
}