Click here to Skip to main content
15,911,890 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a function in my project which fetches different entries. Actually it gets these entries from various tables in a SqlServer DB. These entries are then shown in the fields of a dataGrid. I want to use the function in other forms without rewriting the whole code.

How can I do this and how can I introduce the entries to the functoin?

Thanks a lot!
Posted
Updated 27-Feb-11 21:01pm
v2
Comments
pankajupadhyay29 28-Feb-11 2:58am    
Please clarify the things you want to create control for such requirement or you just want the function to be called from different forms.

If you have common functions move them to a helper class instead of having it in forms.

But still if you want to call the functions in other form, then create instance of that form and call those public functions (Note: If those functions use form global/ instance members, need to make sure those members are initialized).

Here is an optional decoupled way to use a new form and it call back on the caller form.

Use of delegates for form reusability- Dependency injection principle[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 28-Feb-11 3:20am    
Dependency injection is a very good need method, my 5.
I prefer alternative method though, please see my answer.
--SA
Using a dependency injection (and a design pattern of the same name) is a good well-known method.

I prefer a different method which I find a bit simpler. You can create an interface visible in both forms and implement it by the form which methods you want to call. Good thing about it that you can take benefit of partial form declaration. You can created yes another file and in inheritance list add you interface (but not Form — it is declared in other partial declaration inheritance list). You also don't need to add your interface to other files of partial declaration.

Pass just the interface reference to the form to be calling your methods, not reference to the form. In this way, you isolate interface from its implementation. You don't need to make your methods public and pass to much access to one form from another.

C#
//to avoid making implementation of interface methods/properties public, use this form:
void MyInterface.MyMethod(/*...*/) { /*...*/ }

//not this:
public void MyMethod(/*...*/) { /*...*/ }


First method of interface implementation is the best in most cases, not just for interfacing between forms.

—SA
 
Share this answer
 
v2
Comments
Albin Abel 28-Feb-11 4:00am    
Alternative is a better thing, instead of always on the same boat. My 5
Sergey Alexandrovich Kryukov 28-Feb-11 10:22am    
Thank you.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900