1. 程式人生 > >只允許輸入數字的TextBox控制元件

只允許輸入數字的TextBox控制元件

實現效果:

  

知識運用:

  Char結構的IsDigit方法

  TextBox控制元件的KeyPress事件的e(包含事件資料)的KeyChar屬性和Handled屬性

  1, KeyChar屬性  //獲取或設定按下鍵對應的字元

  public char KeyChar{get;set;}  //屬性值: Char結構

  2, Handled屬性  //指示是否處理System.Windows.Forms.Control.KeyPress事件

  public bool Handled{get;set;}

  3, IsDigit方法  //判斷指定字元是否為十進位制數字

  public bool IsDigit(Char c)

  補充:Char結構的IsLetter方法判斷輸入的字元是否為字母

實現程式碼:

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar)) {             //判斷是否為數字
                MessageBox.Show("請輸入數字","提示",
                    MessageBoxButtons.OK,MessageBoxIcon.Information);
                e.Handled = true;                   //取消在控制元件中顯示該字元
            }
        }