2014-12-30 85 views
1

我想在文本框中實現數據庫中名稱是否存在的驗證。我正在用c#使用wpf。我在保存新數據的同時在文本框中實施了驗證。我的問題是在編輯模式下:當我進入編輯模式並嘗試保存時,出現錯誤,名稱已經存在。數據驗證在編輯模式下不起作用

下面的代碼在保存模式下工作正常但是當涉及到數據綁定時的編輯模式錯誤消息顯示。

請建議我一個很好的方法來實現編輯模式下的驗證。

class MyParent 
{ 
    public MyCarClass CurrentCarEntity {get; set;} 

    private void txtName_TextChanged(object sender, RoutedEventArgs e) 
    {    
     CurrentCarEntity.Name = txtName.Text.Trim(); 
     var getName = //Code for getting name from local db 

     if(CurrentCarEntity.Name != Null) 
      { 
       if(getName.Equals(CurrentCarEntity.Name)) 
       { 
        MessageBox.Show("Name Already Exists"); 
       } 
      } 
    } 
} 
+0

你說你已經在你的文本框中實現了驗證,但是在你的問題中沒有看到它。 – learningcs

回答

0

看來你是以下錯誤的做法

讓我們假設我們有一個類叫做用戶喜歡以下

public class User: IValidatableObject 
{ 
    public int Id{get; set;} 
    public string UserName{get; set;} 
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
      if(string.IsNullOrEmpty(UserName)) 
       yield return new ValidationResult("Username field is required!", new string[]{"UserName"}); 
      else 
      { 
       // check if another User has the same username already 
       var db= new YourDbContext(); 
       var exists=db.Users.FirstOrDefault(t=>t.Id!=Id && t.UserName.ToLower()=UserName.ToLower()); 
       if(exists!=null) 
        yield return new ValidationResult("Username is already used by another user!", new string[]{"UserName"}); 
      } 
    } 
} 

你不必擔心編輯或創建,因爲在如果Users表中包含另一個用戶,並且您正在創建或編輯的用戶不是同一用戶,則兩種情況下都檢查數據庫的用戶名相同。

希望這會幫助你

+0

我使用實體框架從數據庫中獲取數據(SQLITE),請告訴我如何爲我的場景實現IDataErrorInfo或IValidatableObject。 @hadi –

+0

@RanjithM我編輯了代碼並添加了IValidatableObject實現 – Monah

+0

@RanjithM您在上面提到的問題標記中使用了WPF,之前我沒有使用過WPF,但是如果它與Windows窗體應用程序相同,那麼您需要來實現實現IDataErrorInfo和IValidatableObject的DataErrorInfo類,兩者都可以一起工作,並且我可以告訴你如果你仍然需要任何幫助 – Monah

1

看起來你正在做驗證失敗,整個形式,如果名稱已經存在 - 驗證將觸發每次嘗試提交(編輯,插入等),因此編輯將總是失敗的時間。

我會製作兩個文本框,一個用於插入,一個用於編輯。在編輯模式下隱藏插入框,或者如果您想堅持使用,至少在編輯時禁用驗證器。

+0

如果我禁用編輯模式下的驗證名稱可能會得到重複,如果用戶輸入一個現有的名稱...有沒有其他方式來做到這一點? –

相關問題