Click here to Skip to main content
15,881,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello
please any one help me...
i currently work in C#
and i want sum help about Page inheritance
so i create
From1:
in this form i have written one Function l.e
public void MyFunction()<br />
{<br />
.............<br />
..............<br />
..............<br />
}

Than i want call that function in another form l.e
Form2<br />
{<br />
MyFunction();<br />
}

thank you.........
please quickly
Posted
Updated 19-Nov-11 4:02am
v3
Comments
Uday P.Singh 19-Nov-11 10:03am    
email address removed to avoid spams

As the question turned out to be very popular, and my previous answers often were not well understood, probably were not clear enough, I decided to write a Tips/Trick article complete with detailed code samples and explanations: Many Questions Answered at Once — Collaboration between Windows Forms or WPF Windows.

—SA
 
Share this answer
 
An extended comment on SAK's remarks on using Interfaces: I am including this in "answer" form, rather than "comment" form, so I can use a little high-lighting in the writing, for emphasis.

I think your continuing exposition/advocacy of using objects/classes/forms instances cast to Interfaces as a way to partially expose/share ... to allow "access" to ... selected contents of one object/class/form by another(s) is an important technique and concept.

Where I sometimes have trouble with the way you explain it is in your use of the word "shared" or statements like "some interface known to both forms" : for example in this thread, the OP's scenario needs only one Form to implement the Interface: the second Form can declare a public instance of it without implementing it.

For an Interface to be "known" to more than one class it usually is in its own class, independent, for example, of any Form definitions. That's best practice, imho, for future code maintainability and OO structure.

Yes, there are two other ways you can define an Interface ... outside its own class ... within the scope of either a NameSpace which happens to contain a Form class definition, or even within a Form Class definition, but use of those, imho, is confusing, and potentially a source of error: if I define an interface inside the scope of Form1's class definition, only an external form, like Form2 in this case, can inherit from it !

or ... if you locate the Interface definition in the file/Namespace that happens to include a Form ... completely outside the scope of the Form's definition ... the Form in that Namespace can, indeed, inherit, from that Interface, but this is really the exact equivalent of defining the Interface in its own class.

Particularly for newcomers here, I think it's very valuable to distinguish between circumstances in which the Interface must be implemented by a class/object/form (a "special mode" of .NET C#'s Inheritance model, if you will), and circumstances in which an Interface definition can be used, and exactly when an instance of a object/class/Form must be cast to an Interface.

I would love to see you write a full-blown CP article, with code examples of course, discussing the relative merits of the strategy of using Interfaces (perhaps focusing on the use case where they must be cast to an instance of the Interface) as a way to expose controlled access, with ideas about "best practices," and scenarios in which you would, and would not, choose this practice over the other types of strategies we so often discuss here: via events; via public static classes, via the delegate-with-static-public-instance technique I show here on this thread.

Perhaps in that article you could also explain your point about the partial class definitions and how they are valuable or relate to Interfaces, which, perhaps, I've never understood, and I suspect other people do not "get," also.

Another, wider-scope, I think, issue of interest in OO design vis-a-vis Interfaces here is ... well, let me frame it with a rhetorical question: at what point when a Class needs access to almost all the Fields, Methods, whatever, of another Class does that become a scenario best implemented by refactoring ... of some form ... like: into a base class which both classes inherit from, or by creating an Interface and passing instances of that Interface ?

As I've said before, I love thinking of work other people could do :)

regards, Bill
 
Share this answer
 
This is a popular question on form collaboration. The most robust approach is implementing of an appropriate interface in a form class. It is especially convenient to use partial class declaration for a form. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].

—SA
 
Share this answer
 
Comments
BillWoodruff 20-Nov-11 1:54am    
+4 Please see my full response to this answer in "Solution 6" below. best, Bill
Sergey Alexandrovich Kryukov 20-Nov-11 14:48pm    
OK, thanks, let me see...
--SA
Here's a different type of solution that shares access to one-and-only-one private method in Form1 in a way it can be called from Form2.

Consider in Form1 you have a TextBox, 'textBox1:
C#
// a delegate defines a signature for a method
public delegate void MyFunctionExposed();

// we create a public static Class-level
// instance of the Type of the delegate
public static MyFunctionExposed mfX;

// this is the private function you want
// to call from Form2
private void MyFunction()
{
    textBox1.Text = "MyFunction on Form1 called";
}

// create a new instance of Form2
Form2 f2 = new Form2();

private void Form1_Load(object sender, EventArgs e)
{
    // show Form2
    f2.Show();

    // assign MyFunction as the value of the static
    // delegate mfX
    mfX = MyFunction;
}
Now, on Form2 which has only a Button, 'button1:
C#
private void button1_Click(object sender, EventArgs e)
{
    // the mfX delegate, ready to execute MyFunction
    // in Form1 is exposed here because it's static and public
    Form1.mfX();
}
Discussion:

1. I believe the minimal amount of "exposure" between objects in different Forms/Clases is a good thing in terms of OO design (separation of concerns). One solution above gives Form2 complete access to everything inside Form1: that will work, but is that "mixing" of total access potentially a source of confusion and errors: some think so. My nickname for solutions that provide some small class access to wide functionality in other classes ... that is not related to the purpose of the small class: "tail wags dog" code :)

2. another valid solution idea described above is provided in the idea of a common class, shared by all forms that implements data or methods needed by all or many Forms.

One strategy is to make that shared class static: there are other scenarios where that shared class must be dynamic, and there you have some interesting complications in terms of making sure ... if there's more than one instance of the shared class ... that the "correct one is being used."

And, to make it more interesting, that shared class could be both dynamic (i.e., created via 'New), and yet have certain static methods or whatever in it.

But, "one size never fits all," even though feet do stop growing after a while :)

Missing from this discussion is any idea of using interfaces, but SAK, I am sure, will take care of that. And ... uh oh ... we left out using Events !
 
Share this answer
 
v2
Comments
RaviRanjanKr 19-Nov-11 13:11pm    
My 5+
Joezer BH 16-Dec-13 1:30am    
5ed!
Uday P.Singh 19-Nov-11 13:13pm    
you beat me to it have a 5+
Sergey Alexandrovich Kryukov 19-Nov-11 17:46pm    
Good solution and discussion of "exposure" between class. Again, I think the best approach is using interfaces, please see my solution.

In fact, for simple applications I would allow for just using internal members and exposing of one form to another, or interface approach for the most robust isolation. I'm afraid a delegate works but does not really add extra benefits. Also, there is no need to use static. And finally, one you problem is violating of Microsoft naming conventions by using names like Form1_Load, button1_Click, etc. Auto-generated names should never be used; and adding a event handler to a event instance should be shown -- anonymous handler method is the best. I voted 4.

--SA
BillWoodruff 19-Nov-11 22:01pm    
SAK: "there is no need to use static." The example shown will not work unless the instance of the delegate 'mfX' is declared static. If 'mfX' were declared public, but not static, then Form2's instance would need access to the instance of Form1 in order to call the method.

SAK: "you problem is violating of Microsoft naming conventions by using names like Form1_Load, button1_Click." Since these names are generated by Visual Studio itself, which I think you'll agree is a Microsoft product, and since this is QA, not a software company where a set of naming convention guidelines is enforced, I think this is a strange digression :)

SAK: "adding a event handler to a event instance should be shown" Why ? I am discussing a technique that does not use Events, and I mention at the end of my answer that this particular answer ignores the possibility of an Event based solution (which I think is not appropriate for this scenario anyway).

If you think an Event based solution is best, in this scenario, using an anonymous handler: please post a code example here; I am sure we will all benefit from your thought and code !

By the way, your writing on QA has been the direct stimulus for my completely re-studying the use of Interfaces, and I deeply appreciate that "eye-opening" !

respectfully, Bill
Solution 2 is correct, however, if the method in Form1 is shared you should consider implementing a common class that can be shared between all forms. An separate assembly will provide you with easier maintenance and extensibility.
 
Share this answer
 
Comments
Uday P.Singh 19-Nov-11 11:40am    
voted 5 for common class suggestion!
If I understand correctly all you will need to do is create an instance of the fist form in the second form or pass a reference of the first form to the second form.

C#
//To create instance of second form inside first form do this i.e.
Form2 form2 = new Form2();
form2.MyFunction();


C#
//to pass a reference to first form into the second form i.e.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        Form2 form2 = new Form2(this);
    }

    public MyFunction()
    {
        // do stuff
    }
}

public partial class Form2 : Form
{
    Form1 mainForm;

    public Form2(Form1 mainForm)
    {
        InitializeComponent();

        this.mainForm = mainForm;
        // call form1 MyFunction()
        mainForm.MyFunction();
    }
}
 
Share this answer
 
v2
Comments
LanFanNinja 19-Nov-11 10:03am    
If you do not understand some part of this leave me a comment and I will try to help you out as soon as I see it.
ram salunke 19-Nov-11 10:08am    
Thank So Much...........
Happy Weekend..
LanFanNinja 19-Nov-11 10:18am    
You're welcome

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