question

lkubler-2593 avatar image
0 Votes"
lkubler-2593 asked lkubler-2593 commented

Refernce method from an instantiated class?

Hi,

In my MainForm class I have a method, Refresh(), that simply makes a call to the backend database and refreshes the data on the form.

In my MainForm I instantiate another class object and on this object are some form elements I display on the main form in a container. One of these is a Save button that writes any changes back to the database and I would also like it to also call the Refresh() method of the MainForm class to refresh all of the data.

My problem is I cannot figure out how to make this call, how do I reference the method from the MainForm class from an instantiated class?

Thanks in advance!

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
0 Votes"
Viorel-1 answered lkubler-2593 commented

Consider the events too. In your another class you can define an event, then raise it after saving the changes to database:

 class AnotherClass
 {
    // . . .
    
    public event EventHandler Saved;
    
    void SaveToDatabase( )
    {
       // . . .
    
       Saved?.Invoke( this, null );
    }
 }

I your main form you can handle this event:

 AnotherClass c = . . .
 c.Saved += ( s, a ) => Refresh( );


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks Viorel-1, that was the clue I needed. Took some research on my part to understand how to implement but I have it working.

0 Votes 0 ·
TimonYang-MSFT avatar image
0 Votes"
TimonYang-MSFT answered

Under normal circumstances, we have two ways to call a method in another class.

One is to instantiate the class:

     class Program
     {
         static void Main(string[] args)
         {
             new MyClass().DoSomething();
         }
     }
     class MyClass
     {
         public void DoSomething() 
         {
             Console.WriteLine("Do something...");
         }
     }

The second is to set the method as a static method, and then access it through the class name:

     class Program
     {
         static void Main(string[] args)
         {
             MyClass.DoSomething();
         }
     }
     class MyClass
     {
         public static void DoSomething() 
         {
             Console.WriteLine("Do something...");
         }
     }

If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.