【问题标题】:How to get text of NumericUpDown before valuechanged event?如何在 valuechanged 事件之前获取 NumericUpDown 的文本?
【发布时间】:2021-11-11 01:10:43
【问题描述】:

我想让它这样工作:当我写入 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。

【问题讨论】:

  • 您不能使用NumericUpDown 控件来接受自然语言输入。我不相信您可以使用NumericUpDown 将输入的"4K" 转换为.Value = 4000。我想你必须为此使用单独的TextBox
  • “但它适用于旧值,现在我写的是” 这是什么意思? FrequencyCW 是什么?您是否从另一个 NUP 控件获取值?旁注:不要将您的控件命名为 NumericUpDown,因为这是类型名称,事情很快就会变得混乱。

标签: c# winforms numericupdown


【解决方案1】:

假设我们有一个名为 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);
}

【讨论】:

  • @Daniel 我不确定我是否理解。现在,如果你输入 1 然后按 k,值变成 1000。这不是你想要的吗?
  • 我想让它像宏一样工作。例如,如果我想得到 NUD1.Value 1000,我应该只写 1K,(当我按 K NUD1.Value 瞬间变为等于 1000 时应该可以工作)。我可以使用 NumericUpDown 吗?
  • @Daniel 重复相同的评论很难回答我的问题。上面的代码究竟是什么不能按预期工作?
  • 非常感谢您的帮助!!!我尝试了这段代码,这几乎可以正常工作。我可以在没有 valuechanged 事件的情况下以某种方式做到这一点。例如,当我写 1 并按 K 时,值应立即变为 1000。但是现在我将值更改为 1,然后将值更改为 1000。问题是我有一些与 valuechanged 事件有关的逻辑(值被发送到设备,它应该发送 1000 而不是 1,然后是 1000)。
  • @Daniel 你看到ValueChanged 事件在上面代码的任何地方使用了吗?不。如果您完全按原样使用上面的代码,您应该在键入 1 后按 k 立即获得 1000。也许您在实际代码中的 ValueChanged 事件中做了其他事情,它正在中断 KeyDown使其无法按预期工作的代码?如果是这样,您可能应该摆脱那部分。
猜你喜欢
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多