正在寻找简洁、直观、惯用的方式来使用 C# 剪辑在 NumericUpDown 控件中设置的值?
我使用下面的代码来实现我想要的功能:当用户在特定 NumericUpDown 控件中编辑值时,并按 k
、K
、m
或 M
,我希望当前输入的金额乘以 1000
。我还希望避免任何溢出异常。这些值应自动限制在最小值
和最大值
。我不想使用 if
语句,因为 min
和 max
函数可用。但是,处理该逻辑需要一些精神能量(将 min
应用到 maximum
和 max
到 minimum
.. .什么?),我觉得我需要留下这样的评论:“警告,这段代码很难阅读,但它可以工作”。这不是我应该写的评论。逻辑太简单了,不需要评论,但我找不到一种显而易见的方式来表达它。有什么建议吗?我可以使用控件本身的设置/方法来完成此任务吗?
private void quantityNumericUpDown_KeyUp(object sender, KeyEventArgs e)
{
if (e.Control || e.Alt)
{
e.Handled = false;
return;
}
if (e.KeyCode != Keys.K && e.KeyCode != Keys.M)
{
e.Handled = false;
return;
}
e.SuppressKeyPress = true;
e.Handled = true;
this.Quantity *= OneThousand;
}
private decimal Quantity
{
get
{
return this.quantityNumericUpDown.Value;
}
set
{
// Sorry if this is not the most readable.
// I am trying to avoid an 'out of range' exception by clipping the value at min and max.
decimal valClippedUp = Math.Min(value, this.quantityNumericUpDown.Maximum);
this.quantityNumericUpDown.Value = Math.Max(valClippedUp, this.quantityNumericUpDown.Minimum);
}
}
I am using the code below to achieve the functionality I desire: when the user is editing a value in a particular NumericUpDown control, and presses either k
, K
, m
, or M
, I want the currently entered amount to multiply by 1000
. I also wish to avoid any overflow exceptions. The values should automatically cap at a minimum
and a maximum
. I did not want to use if
statements because min
and max
functions are available. But, it takes some mental energy to process that logic (applying min
to maximum
and max
to minimum
... what?), and I felt like I needed to leave a comment along the lines of: 'warning, this code is hard to read but it works'. This is not the sort of comment that I should be writing. The logic is too simple to need a comment, and yet I cannot find a self-apparent way to express it. Any suggestions? Could I use settings/methods of the control itself to get this done?
private void quantityNumericUpDown_KeyUp(object sender, KeyEventArgs e)
{
if (e.Control || e.Alt)
{
e.Handled = false;
return;
}
if (e.KeyCode != Keys.K && e.KeyCode != Keys.M)
{
e.Handled = false;
return;
}
e.SuppressKeyPress = true;
e.Handled = true;
this.Quantity *= OneThousand;
}
private decimal Quantity
{
get
{
return this.quantityNumericUpDown.Value;
}
set
{
// Sorry if this is not the most readable.
// I am trying to avoid an 'out of range' exception by clipping the value at min and max.
decimal valClippedUp = Math.Min(value, this.quantityNumericUpDown.Maximum);
this.quantityNumericUpDown.Value = Math.Max(valClippedUp, this.quantityNumericUpDown.Minimum);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样写,让 updown 控件的最小值和最大值为您处理。
Write it like this and let the min and max value of the updown control handle it for you.