首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 僅接受數字輸入的控制項 (五) NumericUpDown

     編輯:關於C語言

使用 NumericUpDown 控制項

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 設計師,所有屬性均可在設計介面直接設定,無需手寫代碼。

截圖

NumericUpDown 執行畫面

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved