Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic calling of members 1

Status
Not open for further replies.

robertkjr3d

Programmer
Dec 19, 2003
36
US
How do I programmatically call a member of an unknown type?

I have form A... which opens up another form B. However Form A will be the parent of B.

In fact I have this code:
Code:
listing list1 = new listing();
list1.parent = this;
list1.Show();

In list1 parent is an object. Because it could come from any number of forms.

Now in the 'listing' code... I want to call a member of parent... unfortunately I can't do this normally by either:

Code:
parent.whatever = 0;
gives the compile error that object parent contains no definition of 'whatever'.

The other way that I know will work is to have a series of if/case statments that figure out where it did come from:
Code:
if (source == "Referral") 
{
    Referral r = (Referral)parent;
    r.whatever = 0; //and this will work
}

But isn't there a way I can programmatically find the objects and call them of the object parent without having to know before compile time what form is the parent?

Of course I would make sure that all the 'Parents' would have the 'whatever' I'm trying to reference. But I shouldn't have to know.. or use a series of case or if statements to do this.

-Robert
 
Ok, you are about to enter the world of Interfaces.

You could do .GetType() and switch the type but what a pain!

Instead, create an interface and pass that in.

public interface IMyInterface
{
int whatever{get; set;}
}

then your form can use IMyInterface:

public Form1 :System.Windows.Forms.Form, IMyInterface
{
private int mywhatever = 0;

public Form1()
{
InitializeComponent();
}

public int whatever
{
get
{
return mywhatever;
}
set
{
mywhatever = value;
}
}
}


Then in your Listing Form you would put this:

public Listing : System.Windows.Forms.Form
{
IMyInteface callingform;

public void SetCallingForm(IMyInterface frm)
{
callingform = frm;
}


private void Button1_Click(object sender, EventArgs e)
{
callingform.whatever = 1000;
}
}


Now you can pass in a form, a class, a customcontrol, anything that used IMyInterface.
 
Can I also call a function that way...

In earlier code... if I didn't get the compile error it would be:

Code:
parent.go();
How would I call a function undernearth an unknown form with this interface stuff?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top