簡體   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