我想讓它這樣作業:當我寫入 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。
uj5u.com熱心網友回復:
假設我們有一個名為 的 NumericUpDown numericUpDown1。每當用戶按下 時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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/357988.html
