NumericUpDown 是 .NET Framework 內建的控制項,專為數值輸入設計,內建上下按鈕可步進調整數值,且支援千分位分隔符、最大/最小值限制等屬性,是處理純數字輸入最直接的選擇。
using System;
using System.Drawing;
using System.Windows.Forms;
sealed class TestForm : Form
{
private NumericUpDown m_numericUpDown;
public TestForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.m_numericUpDown = new NumericUpDown();
this.m_numericUpDown.Value = 100;
this.m_numericUpDown.Dock = DockStyle.Fill;
this.m_numericUpDown.ThousandsSeparator = true;
this.m_numericUpDown.Maximum = int.MaxValue;
this.ClientSize = new Size(100, 60);
this.Controls.Add(this.m_numericUpDown);
this.PerformLayout();
}
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TestForm());
}
}
Value:設定或取得目前數值,型別為 decimal。ThousandsSeparator:是否顯示千分位分隔符(逗號)。Maximum / Minimum:限制輸入範圍。DecimalPlaces:小數位數(預設為 0)。當使用者輸入不符合要求的字元時,預設行為是發出蜂鳴聲(Beep),不會顯示工具提示。若使用 Visual Studio 設計師,所有屬性均可在設計介面直接設定,無需手寫代碼。
