LinqDataSource.Inserting 事件

定義

在插入作業之前發生。

public:
 event EventHandler<System::Web::UI::WebControls::LinqDataSourceInsertEventArgs ^> ^ Inserting;
public event EventHandler<System.Web.UI.WebControls.LinqDataSourceInsertEventArgs> Inserting;
member this.Inserting : EventHandler<System.Web.UI.WebControls.LinqDataSourceInsertEventArgs> 
Public Custom Event Inserting As EventHandler(Of LinqDataSourceInsertEventArgs) 

事件類型

範例

下列範例示範在插入作業之前修改資料之事件的事件處理常式 Inserting 。 屬性中的 NewObject 物件會轉換成名為 Product 的類型。 物件的 DateModified 屬性 Product 會設定為目前的日期和時間。

protected void LinqDataSource_Inserting(object sender, LinqDataSourceInsertEventArgs e)
{
    Product product = (Product)e.NewObject;
    product.DateModified = DateTime.Now;
}
Protected Sub LinqDataSource_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LinqDataSourceInsertEventArgs)
    Dim product As Product
    product = CType(e.NewObject, Product)
    product.DateModified = DateTime.Now
End Sub

下列範例顯示擷 Inserting 取驗證例外狀況之事件的事件處理常式。

Protected Sub LinqDataSource_Inserting(ByVal sender As Object, _  
        ByVal e As LinqDataSourceInsertEventArgs)  
    If (e.Exception IsNot Nothing) Then  
        For Each innerException As KeyValuePair(Of String, Exception) _  
               In e.Exception.InnerExceptions  
            Label1.Text &= innerException.Key & ": " & _  
                innerException.Value.Message & "<br />"  
        Next  
        e.ExceptionHandled = True  
    End If  
End Sub  
protected void LinqDataSource_Inserting(object sender,   
        LinqDataSourceInsertEventArgs e)  
{  
    if (e.Exception != null)  
    {  
        foreach (KeyValuePair<string, Exception> innerException in   
             e.Exception.InnerExceptions)  
        {  
        Label1.Text += innerException.Key + ": " +   
            innerException.Value.Message + "<br />";  
        }  
        e.ExceptionHandled = true;  
    }  
}  

上述範例會擷取驗證例外狀況。 如果值不符合 屬性的類型,可能會擲回例外狀況。 它也可能從自訂檢查擲回,例如下列範例中的檢查。 方法 OnAgeChanging 會檢查 屬性的數位不是負數 Age

partial void  OnAgeChanging(int? value)  
{  
    if (value < 0)  
    {  
        throw new Exception("Age cannot be a negative number.");  
    }  
}  
Private Sub OnAgeChanging(ByVal value As System.Nullable(Of Integer))  
    If (value < 0) Then  
        Throw New Exception("Age cannot be a negative number.")  
    End If  
End Sub  

備註

Inserting處理事件來驗證要插入的物件、檢查資料類別中的資料驗證錯誤、變更插入作業之前的值,或取消插入作業。 LinqDataSourceInsertEventArgs傳遞給這個事件的事件處理常式的物件包含要插入資料來源的新物件。

如果在插入作業期間發生驗證錯誤, LinqDataSourceInsertEventArgs 物件就會包含資料類別擲回的驗證例外狀況。 如果要插入的值不符合資料類別中的屬性類型,或未通過自訂驗證檢查,就會發生驗證錯誤。 在事件的事件處理常式中 Inserting ,您可以擷取驗證例外狀況並採取適當的動作。

如果在事件的事件處理常式 Inserting 中擲回例外狀況,您必須處理該事件處理常式中的例外狀況。 例外狀況不會透過物件) ExceptionLinqDataSourceStatusEventArgs 屬性,傳遞至事件的事件處理常式 Inserted (。 屬性 Exception 只包含事件之後擲回的 Inserting 例外狀況。

適用於