C# 如何讓TextBox只允許輸入數字

首先,在窗體.Designer.cs中寫入下面一行程序:

this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(textBox1_KeyPress);


然後,在窗體代碼中寫入以下程序:

private void textBox1_KeyPress(object sender,KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar))//判斷是否爲數字
            {
                MessageBox.Show("請輸入數字!");
                e.Handled = true;//取消顯示該字符
            }
        }


OK!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章