控制winform文本框輸入字符限制(數字或字母、長度)

使用keyPress事件效果比keydown效果要好 

private void txtDBThempLibName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Back) {
                e.Handled = false;
                return;
            }
            string pattern = @"^[a-zA-Z0-9]{0,6}$";
            if (!Regex.IsMatch(txtDBThempLibName.Text.Trim(), pattern))
            {
                MessageBox.Show("輸入格式不正確,請檢查:\r\n請檢查輸入是否爲數字或字母以外的符號");
                return;
            }
            if (txtDBThempLibName.Text.Trim().Length>0)
                btnImport.Enabled = true;
            else
                btnImport.Enabled = false;
            if (txtDBThempLibName.Text.Length >= 6) e.Handled = true;
        }

發佈了66 篇原創文章 · 獲贊 5 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章