NumericUpDown
NumericUpDown
应该是此问题的默认选择,您可以在其中保留实际值并控制要显示的内容。在您的情况下,将 DecimalPlaces
属性设置为 0
(默认值)并将 Minimum
和 Maximum
属性设置为 Decimal.MinValue
和 {{3} } 分别。
public YourForm()
{
InitializeComponent();
numericUpDown1.Maximum = decimal.MaxValue;
numericUpDown1.Minimum = decimal.MinValue;
numericUpDown1.DecimalPlaces = 0; // Default...
// The same for the other numeric controls...
}
或者,子类设置默认值:
public class MyNumericUpDown : NumericUpDown
{
public MyNumericUpDown()
{
Minimum = decimal.MinValue;
Maximum = decimal.MaxValue;
}
/// <inheritdoc cref="NumericUpDown.Minimum"/>
[DefaultValue(typeof(decimal),"-79228162514264337593543950335")]
public new decimal Minimum { get => base.Minimum; set => base.Minimum = value; }
/// <inheritdoc cref="NumericUpDown.Maximum"/>
[DefaultValue(typeof(decimal),"79228162514264337593543950335")]
public new decimal Maximum { get => base.Maximum; set => base.Maximum = value; }
}
Decimal.MaxValue
文本框
如果旋转框不是一个选项并且您需要使用 TextBox
。创建一个新类并继承 TextBox
控件,添加一个小数属性来存储实际值,并使用它的 setter 将值的整数部分分配给 Text
属性。如果您允许文本编辑/粘贴,您还需要覆盖 OnValidating
方法来验证输入,如下所示。
[DefaultEvent("ValueChanged")]
[DefaultProperty("Value")]
[DesignerCategory("Code")]
public class IntTextBox : TextBox
{
public IntTextBox() : base()
{
//Comment if you allow text edit/paste...
ReadOnly = true;
BackColor = SystemColors.Window;
}
private decimal _value;
[DefaultValue(typeof(decimal),"0")]
public decimal Value
{
get => _value;
set
{
if (_value != value)
{
_value = value;
Text = Math.Truncate(value).ToString();
OnValueChanged(EventArgs.Empty);
}
}
}
protected override void OnValidating(CancelEventArgs e)
{
base.OnValidating(e);
if (ReadOnly) return;
// Change as required...
if (Text.Trim().Length == 0) Value = 0;
else if (decimal.TryParse(Text,out var res))
{
if (res % 1 != 0 && res != _value) Value = res;
else if (res != Math.Truncate(_value)) Value = res;
}
else
Text = Math.Truncate(Value).ToString();
}
// Handle this in the host instead of the TextChanged event if you need so...
public event EventHandler ValueChanged;
protected virtual void OnValueChanged(EventArgs e) =>
ValueChanged?.Invoke(this,e);
}
使用此自定义 TextBox
,忘记 Text
属性并改用 Value
属性来设置/获取值。
,
在文本框的“Tag”属性中保留初始值并将其用作实际值:
double result = height * rate;
textbox1.Text = String.Format("{0:N0}",result.ToString());
textbox1.Tag = result;
//...
double actualValue = double.Parse(textbox1.Tag.ToString());
本文链接:https://www.f2er.com/76269.html