views:

730

answers:

2

I have a windows form with a data grid bound to a datatable. On a button click, the data table is passed to a static class.

private void btnSave_ItemClick(object sender, EventArgs e)
{
   MyStaticClass.SaveData(DataTable dt);
}


internal static class MyStaticClass
{
    internal static void SaveData(DataTable dt)
    {
       foreach(DataRow dr in dt.rows)
       {
           // do something    
       }
    }
}

I need to pass back status information from the SaveData method back to my form so that I can inform the user how record is being processed.

say for example - I want to send back a message every 100 records - "processing record #...." so that it is displayed on the form.

is it possible to raise an event from a static class?

+1  A: 

Yes, you can raise an event from your static class. Define the event as static.

public static event EventHandler MyEvent;
Hemanshu Bhojak
+2  A: 

Yes it is possible and works just like events in non-static classes do (except that you, of course, need to declare the event with as being static).

Note though that through this design, you can (at least in theory) have several forms calling SaveData simultanteously, so one instance of the method is raising events targeted for Form A, while another instance will be raising events targeted for Form B. Since the event is static, all events will be caught by both forms, so you may want to include information in event that the form can use to determine whether a particular invocation of the event is of interest or not.

You could, for instance, put together a custom EventArgs class and pass the DataTable in that, so that the listening code can see if it is the DataTable from that form. If it is, the UI will be updated, if it's not the call can simply be ignored.

Fredrik Mörk