繁体   English   中英

如何在 valuechanged 事件之前获取 NumericUpDown 的文本?

[英]How to get text of NumericUpDown before valuechanged event?

我想让它这样工作:当我写入 NumericUpDown 1k 时,该值应该是 1000,当我写入 4M 时,该值应该是 4000000。我怎样才能做到呢? 我试过这个:

private void NumericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyValue == (char)Keys.K)
    {
        NumericUpDown1.Value = NumericUpDown1.Value * 1000;
    }
}

但它适用于我写的原始值。

我想让它像宏一样工作。 例如,如果我想得到 NUD1.Value 1000,我写 1,然后当我按下 K 时 NUD1.Value 变成 1000。

假设我们有一个名为numericUpDown1的 NumericUpDown。 每当用户按下k 时,我们希望将 NUP 的当前值乘以 1,000,如果用户按下m ,则当前值应乘以 1,000,000。 我们也不希望原始值触发ValueChanged事件。 因此,我们需要有一个bool变量来指示该值正在更新。

这是一个完整的例子:

private bool updatingValue;

private void numericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData != Keys.K && e.KeyData != Keys.M) return;

    int multiplier = (e.KeyData == Keys.K ? 1000 : 1000000);

    decimal newValue = 0;
    bool overflow = false;
    try
    {
        updatingValue = true;
        newValue = numericUpDown1.Value * multiplier;
    }
    catch (OverflowException)
    {
        overflow = true;
    }
    updatingValue = false;

    if (overflow || newValue > numericUpDown1.Maximum)
    {
        // The new value is greater than the NUP maximum or decimal.MaxValue.
        // So, we need to abort.
        // TODO: you might want to warn the user (or just rely on the beep sound).
        return;
    }

    numericUpDown1.Value = newValue;
    numericUpDown1.Select(numericUpDown1.Value.ToString().Length, 0);
    e.SuppressKeyPress = true;
}

ValueChanged事件处理程序应该是这样的:

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    if (updatingValue) return;

    // Simulating some work being done with the value.
    Console.WriteLine(numericUpDown1.Value);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM