萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# TextBox 僅允許輸入數字(含小數點)的 KeyPress 實現

核心代碼

private void txtNumber_KeyPress(object sender, KeyPressEventArgs e)
{
    TextBox tb = sender as TextBox;
    // 允許:數字鍵(48-57)、退格鍵(8)、小數點(.)
    // 限制:只能有一個小數點
    if (e.KeyChar == '.' && tb.Text.IndexOf('.') >= 0)
    {
        e.Handled = true; return;
    }
    if (!((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == '.' || e.KeyChar == '\b'))
    {
        e.Handled = true;
    }
}

綁定事件

設計器屬性窗口 → 事件 → KeyPress → 選擇 txtNumber_KeyPress,或代碼綁定:

this.txtNumber.KeyPress += txtNumber_KeyPress;

擴展:支持負號

if (e.KeyChar == '-' && tb.SelectionStart == 0 && !tb.Text.Contains("-"))
    return; // 允許開頭輸入負號

替代方案

  • MaskedTextBox:設置 Mask="999.99" 等格式。
  • NumericUpDown:純整數/小數增減控件。
  • WPF:PreviewTextInput + 正則驗證。
copyright © 萬盛學電腦網 all rights reserved