Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0
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()
{
.............
..............
..............
}

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

thank you.........
please quickly
Posted 19-Nov-11 3:45am
Edited 19-Nov-11 4:02am
v3
Comments
Uday P.Singh at 19-Nov-11 10:03am
   
email address removed to avoid spams
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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.
 
//To create instance of second form inside first form do this i.e.
Form2 form2 = new Form2();
form2.MyFunction();
 
//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();
    }
}
  Permalink  
v2
Comments
LanFanNinja at 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 at 19-Nov-11 10:08am
   
Thank So Much...........
Happy Weekend..
LanFanNinja at 19-Nov-11 10:18am
   
You're welcome
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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.
  Permalink  
Comments
Uday P.Singh at 19-Nov-11 11:40am
   
voted 5 for common class suggestion!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

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
  Permalink  
Comments
BillWoodruff at 20-Nov-11 1:54am
   
+4 Please see my full response to this answer in "Solution 6" below. best, Bill
SAKryukov at 20-Nov-11 14:48pm
   
OK, thanks, let me see...
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

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:
// 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:
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 Smile | :)
 
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 Smile | :)
 
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 !
  Permalink  
v2
Comments
RaviRanjankr at 19-Nov-11 13:11pm
   
My 5+
Canny Brisk at 16-Dec-13 1:30am
   
5ed!
Uday P.Singh at 19-Nov-11 13:13pm
   
you beat me to it have a 5+
SAKryukov at 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 at 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
SAKryukov at 20-Nov-11 15:06pm
   
Thank you, Bill.
 
There is certainly no need to use static, bust because two instances of the forms are involved already. Whatever you can do with static can be done as non-static. I could demonstrate it if it was interesting, but I'll do it if you point out some logical reason why this is not possible, not just "would nee access to the instance". Static is bad in principle: it would be harder to generalize to the case with more instances, it might needs special measures to make code thread-safe, etc. Generally, static is overused by many just because of lack of understanding how to make things using instance (non-static) member and underestimation of potential problems.
 
"Since these names are generated by Visual Studio itself". If proofs nothing. Such code will not pass FxCop check. Why do you think what is generated by Visual Studio is acceptable? Yes, its is generated, but the use of it without renaming is explicitly non recommended by Microsoft via published naming conventions, coding best practice rule, formally used by FxCop. It's supposed that the developers renames all such name. Refactoring engine is provided for this and similar purposes. We need to use these recommendation and testing by FxCop, for our own good.
 
Adding an event handler to an event instance should be shown, because this is one of the typical kinds of confusions here on CodeProject Questions and Answers. First, many members fail to understand that button1_Click is not an event, but Button.Click is. Also, sometimes people remove the handler but the handler method remain in the code; and they get confused why it is not called. Finally, I notices that some members thing that having a function with appropriate signature and name itself means handling an event. We should not promote such deep confusions. I would not require showing appropriate code if I did not have experience dealing with such confusion in real-life CodeProject practice.
 
"If you think an Event based solution is best". Summary: your arguments did not convince me. I still think interface method is better by more than one reason.
 
Thank you for this discussion.
 
Cheers,
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

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 Smile | :)
 
regards, Bill
  Permalink  

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 6,745
1 OriginalGriff 6,696
2 CPallini 5,315
3 George Jonsson 3,599
4 Gihan Liyanage 2,650


Advertise | Privacy | Mobile
Web02 | 2.8.140922.1 | Last Updated 20 Nov 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100