2013-06-28 27 views
0

我正在使用FormView控件,並且我想通過FormValues的FormViewUpdateEventArgs參數中的NewValues dictioanry以編程方式在OnItemInserting和OnItemUpdating事件中插入空值。但如果我使用FormView,在OnItemInserting或OnItemUpdating事件中以編程方式插入null

protected void FormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) 
{ 
    e.NewValues["EntityFrameworkEntityPropertyName"] = null; 
} 

這樣的修改被忽略,數據庫列不更新並保持其舊值。 EntityFramework實體屬性爲:類型Int32,可空Nulllable,StoreGeneratedPattern無。

如果我通過Bind()將TextBox控件直接綁定到屬性,那麼插入的就是空值。此外,如果值與null不同,則一切正常。

如何插入空值?

回答

0

好吧,我找到了解決方案。 DetailsViewFormViewOnItemUpdating事件比較先前和新值,如果這些更改,更新它。當我將null填入e.NewValues時,雖然我的TextBox不受Bound函數的限制,但e.OldValues["EntityFrameworkEntityPropertyName"]不存在(表示空),並且在NewValues中也爲空,因此列未更新。

我簡單地將e.OldValues["EntityFrameworkEntityPropertyName"]設置爲任何(但相同類型),現在插入空值工作正常。

protected void FormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) 
{ 
    e.OldValues["EntityFrameworkEntityPropertyName"] = -1 
    e.NewValues["EntityFrameworkEntityPropertyName"] = null; 
} 

我的文本框不是直接限定的,因爲我需要在將它展示給用戶之前處理它的值。在插入/更新時,我還需要一些值處理。

0

嘗試像

e.NewValues["EntityFrameworkEntityPropertyName"] = System.DBNull.Value; 
+0

這引發異常DBNull不能轉換爲Int32 nillable(通過實體框架)。 – Fanda