views:

31

answers:

2

Hi all,

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.ExceptionHandled;
        }
    }

    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.

A: 

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

TheGeekYouNeed
That sounds like it would work but I'd like to try and not tie myself to having to call the buttons certain names as this is part of a framework that will be used by many other developers and I know in time the reason for calling the buttons certain names will become lost.
Daniel
then call them whatever you want and handle that in the code
TheGeekYouNeed
+1  A: 

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;
    }

}
matt-dot-net
That's awesome thats exactly what I want...problem is we are on .net 3.5 :( Oh well thanks for that matt
Daniel