2

How to access private methods from one form to another form?

For Example I have this method in Form1:

Form1:

private void Test (){}

Then how to access that method (private void Test) in Form2 so that that values that I entered in Form2 will be sent in the method Test??

Test is a datagridview and in form 2 I have to enter Name with corresponding values in it and if I press the save button, it should be automatically save in the datagridview which in in Form1.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
James
  • 271
  • 1
  • 3
  • 13
  • So it should be public void Test () {}??Then what should be the code in Form2 then?? – James Mar 04 '16 at 06:37
  • No you can't access `private` things outside of that class – Mangesh Mar 04 '16 at 06:38
  • First of all: Give good names. If you continue your program with `Form1` and `Form2` you'll have a big problem later, when you didn't touched you code for a while. – Mischa Mar 04 '16 at 06:43
  • @James, you can use reflection to access private method – Kira Mar 04 '16 at 06:49
  • 1
    Linked http://stackoverflow.com/questions/135443/how-do-i-use-reflection-to-invoke-a-private-method (as duplicate) shows how to do exactly what you are asking. Please note that in most cases there are much better approaches to each concrete case - unfortunately it is not possible to suggest as you've not provided reasons why it is private and your ultimate goal. – Alexei Levenkov Mar 04 '16 at 06:59
  • [How do you unit test private methods?](http://stackoverflow.com/q/250692/18192) is a similarly helpful duplicate, but is more directly relevant to the OP. – Brian Mar 04 '16 at 14:09

3 Answers3

5

private method is not meant to be accessed outside of its class at all. You cannot access private method if you are not in the class.

The simplest way for your case would be to make the private method public

public void Test (){}

Alternatively, you have to make a public wrapper method to call your private method:

public void TestWrapper() {
    Test(); //if test is private
}

And then in your Form2, you should have the instance of Form1 and call the method easily like this:

//All these are inside Form2
Form1 form1 = new Form1();

//Somewhere in your code
form1.Test(); //if test is public, or
form1.TestWrapper(); //if test is private

But in all cases, the bottom line is:

You cannot call private method outside of the class.

Ian
  • 30,182
  • 19
  • 69
  • 107
0

If you want to access the method of other form then it can not be private. You need to make them as public to access the method of other form.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

you can't access private method from another class. make it public then you can access it through another class.

Rakibul Hasan
  • 61
  • 2
  • 9