方法①:使用 ValidatingEditor 事件(一般用於對整個GridView內的文本框進行數據驗證)
當單元格輸入格式錯誤時,直接在該行下方提示,代碼如下:

using System.Text.RegularExpressions; //注意添加引用 private void gridView1_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e) { if (gridView1.FocusedColumn == colcount) //設置校驗列 { bool result = false; Regex regex = new Regex(@"^\+?\d+$"); result = regex.IsMatch(e.Value.ToString()); if (!result) { e.ErrorText = "請輸入一個正整數"; e.Valid = false; return; } } }
效果如下:
方法②:使用 ValidatingEditor 事件進行驗證,InvalidValueException 事件進行錯誤信息提示(一般用於對整個GridView內的文本框進行數據驗證)
當單元格輸入格式錯誤時,彈出消息看提示,代碼如下:

using DevExpress.XtraEditors.Controls; //注意添加引用 private void gridView1_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e) { DataRow dr = gridView1.GetFocusedDataRow(); if (gridView1.FocusedColumn == colcount) { bool result = false; Regex regex = new Regex(@"^\+?\d+$"); result = regex.IsMatch(e.Value.ToString()); if (!result) { e.Valid = false; } } } private void gridView1_InvalidValueException(object sender, DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e) { e.ExceptionMode = ExceptionMode.DisplayError; e.WindowCaption = "輸入錯誤"; e.ErrorText = "請輸入一個正整數"; gridView1.HideEditor(); }
效果如下:
方法③:使用 RepositoryItemTextEdit 的 Validating 事件進行驗證,InvalidValueException 事件進行錯誤信息提示(一般用來對內置控件的單元格進行數據驗證)
當單元格輸入格式錯誤時,彈出消息看提示,代碼如下:

private void repositoryItemTextEdit1_Validating(object sender, CancelEventArgs e) { //將sender轉換為BaseEdit類型,使用EditValue來獲取當前輸入的值並進行校驗 BaseEdit textEdit = sender as BaseEdit; if (textEdit.EditValue.ToString().Trim().Length > 0) { bool result = false; Regex regex = new Regex(@"^\+?\d+$"); result = regex.IsMatch(textEdit.EditValue.ToString()); if (!result) { e.Cancel = true; //校驗不通過 return; } } } private void gridView1_InvalidValueException(object sender, DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e) { e.ExceptionMode = ExceptionMode.DisplayError; e.WindowCaption = "輸入錯誤"; e.ErrorText = "請輸入一個正整數"; gridView1.HideEditor(); }
效果如下: