[C#]DataGridView欄位驗證只能是數字且不能為空白

  • 29522
  • 0
  • 2010-08-02

DataGridView欄位驗證只能是數字且不能為空白

這是在藍色小舖遇到的問題,問題如下

想請一下,若是在DataGridView欄位驗證
非數字的話,就return
該怎麼驗證呢!
因為以下判斷並無法在CellEndEdit事件裡使用!
string Num = "";
Regex r = new Regex("^[1-9][0-9]*[\\.]?[0-9]*$", RegexOptions.Compiled);

為了解決這個問題,我寫了一個函式,將cell傳入,之後會將有問題的cell顯示其error message,並且return是否符合驗證規則 

       private bool ValidaCell(DataGridViewCell cell)
        {
            cell.ErrorText = "";
            if (dgvList.Rows[cell.RowIndex].Cells[0].Value == null || dgvList.Rows[cell.RowIndex].Cells[0].Value.ToString() == "")
            {
                return true;
            }


            if (cell.Value == null || cell.Value.ToString() == "")
            {
                cell.ErrorText = "不允取填入空白";
                return false;
            }


            System.Text.RegularExpressions.Regex regul = new System.Text.RegularExpressions.Regex(@"[0-9]");
            if (!regul.IsMatch(cell.Value.ToString()))
            {
                cell.ErrorText = "只允許填入數字";
                return false;
            }

            return true;
        }

 

可以在程式中調用它

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            foreach (DataGridViewRow row in dgvList.Rows)
            {

                if (row.IsNewRow) continue;
                if (row.Cells[0].Value == null || row.Cells[0].Value.ToString() == "")
                {
                    dgvList.Rows.Remove(row);
                    continue;
                }

                foreach (DataGridViewCell cell in row.Cells)
                {
                    ValidaCell(cell); // 您可以透過 if(ValidaCell(cell))來做您想要的事情
                }

            }

            dgvList.Refresh();
        }

執行結果


輸入空白時

輸入數字外的資料時

參考

http://www.blueshop.com.tw/board/show.asp?subcde=BRD200902130200323P8&fumcde=

檔案下載

驗證欄位資料內容.rar