.NET菜鳥自救會

歡迎來到小歐ou的網誌,這裡紀錄我的學習心得與技術分享
文章數 - 251, 回應數 - 383, 引用數 - 0

網摘、引用、連結,不轉載

Creative Commons License

每月文章

文章分類

Plruk 機器人

個人部落格

常用連結

技術網站

技術部落格

[C#]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

 


posted on 2009/2/16 10:15 | 我要推薦 | 閱讀數 : 3935 | 文章分類 [ C# ] 訂閱

Feedback

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

DataGridView是DataGrid,還是GridView,還是新的東西呢?

2009/2/16 上午 10:54 | hatelove

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

驚!是winform的!

哈,看來是我孤陋寡聞了~

PS:如果是Web Form的可以用一下RequiredFieldValidator跟CompareValidator或RegulrExpressionValidtor,來驗證必要輸入跟輸入格式

2009/2/16 上午 10:57 | hatelove

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

To hatelove 大大

的確在Web Form可以透過您說的方式來做,不過WinForm就比較麻煩點

2009/2/16 下午 02:12 | chou

回應

標題
姓名
電子郵件 (將不會被顯示)
個人網頁
內容 
  登入後使用進階評論  
Please add 2 and 1 and type the answer here:

Powered by: