开发者

DetailsView Item events (updated deleted) with same handler

开发者 https://www.devze.com 2023-01-07 13:27 出处:网络
I\'m using a details view in my asp.net web application. When it fires its updated and inserted events I\'d like to handle them the same way. Because the event args they have are two separate classes

I'm using a details view in my asp.net web application.

When it fires its updated and inserted events I'd like to handle them the same way. Because the event args they have are two separate classes with no common inheritance I have to have two separate methods with basically the same code.

Is there any way around this?

eg.

protected void DetailsViewItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        if (e == null)
            return;

        if (e.Exception != null)
        {
            e.ExceptionHandled = HandleException(e.Exception);
            e.KeepInInsertMode = e.ExceptionHand开发者_开发知识库led;
        }
    }

    protected void DetailsViewItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
    {
        if (e == null)
            return;

        if (e.Exception != null)
        {
            e.ExceptionHandled = HandleException(e.Exception);
            e.KeepInEditMode = e.ExceptionHandled;
        }
    }

I'd like to extract if (e == null) return;

        if (e.Exception != null)
        {
            e.ExceptionHandled = HandleException(e.Exception);
            e.KeepInEditMode = e.ExceptionHandled;
        }

into some kind of common method if possible.


I agree it is disappointing that these classes inherit directly from EventArgs. It seems logical that they would inherit from the same sublass of EventArgs given not just their common properties, but the fact that most times you use a DetailsView for inserting you also use it for updating.

That being said, what you want to do can be accomplished with a bit of dynamic C#. It's pretty cool, and maybe even a little elegant, albeit a little more overhead.

Try this: (requires C# 4.0)

protected void DetailsView1_Inserted(Object sender, DetailsViewInsertedEventArgs e)
{
    ProcessDetailsViewEventArgs(e);
}

protected void DetailsView1_Updated(Object sender, DetailsViewUpdatedEventArgs e)
{
    ProcessDetailsViewEventArgs(e);
}

private void ProcessDetailsViewEventArgs(dynamic e)
{
    if (e == null)
        return;

    if (e.Exception != null)
    {
        e.ExceptionHandled = HandleException(e.Exception);
        e.KeepInEditMode = e.ExceptionHandled;
    }

}


Use the OnItemCommand, & give your Edit & Delete buttons CommandNames. This event will handle both scenarios for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号