Simple Class/Form Question

T

Typpo

Hi,

This question is somewhat basic. Is it possible to call a method in
frmMain, using another class? Here's a snippet:

partial class frmMain : Form
{
private void MessageThis(String text)
{
MessageBox.Show(text);
}
}

public class AnotherClass
{
public AnotherClass(text)
{
frmMain.MessageThis(text); //doesn't work
MessageThis(text); //doesn't work
//and so on...
}
}

I've dabbled with public and static methods, etc, but I can't seem to
find the correct way.

Thanks.
 
B

Bob Grommes

MessageThis() is private, which means it can only be called from frmMain.

Making it public will make it callable from AnotherClass, but only if
AnotherClass has an instance of frmMain available to it, for example:

frmMain frm = new frmMain();
frm.MessageThis(text);

The above is a trivial example to get the idea across of needing an instance
variable to call the method from. I realize that you wouldn't likely
actually use it the way I illustrate.

Making MessageThis() public AND static would make it callable as
frmMain.MessageThis() (that is, will make the method available from the
class itself without requiring an instance) but I presume that MessageThis()
is supposed to receive a message on behalf of an instance of frmMain; if so,
then making the method static wouldn't work because the method wouldn't then
have access to instance data of frmMain.

If you could explain what you're actually trying to accomplish perhaps we
could find a way to your solution.

--Bob
 
T

Typpo

Using the following code:

frmMain frm = new frmMain();
frm.MessageThis(text);

Works fine. The problem is, I'm creating a new form in the process and
frm.Show() reveals a duplicate. The method is called correctly,
however, and the intended effect takes place on the duplicate form. The
original form isn't changed at all.

I'm sorry if I was vague. Here's what I am trying to do...

On the main form, the user presses a button that loads a dialog form
that he or she fills out. The dialog form creates a new class that
organizes the information, and I would like to have the class or the
dialog form call a method contained in the main form's class. This
method adds the information to a list on the main form.

Thanks for your help. I hope I'm making sense =/.
 
N

news.microsoft.com

Why don't you just pass a reference to your class object to the dialog form
so it can provide the information back to your main form.

Greg
 
T

Typpo

Sorry Greg, I'm not sure what you mean by that. I have an array of
class objects.

How would I pass, say, myClass[2] to the dialog form and have it return
the info filled out back to the main form?

Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top