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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Modify a form's control properties from a class

Status
Not open for further replies.

carlossan

Programmer
Dec 10, 2005
18
CA
Hello,

If I have a class that does some calculations and I want to show the result of those calculations on a form's textbox, how can I do that ?

I have tried writing the following on the class, but it doesn't work:

form1.textbox1.text = showData(initialValues);

Where show data is one of the class' methods and it returns a string.

form1 also shows some other data that doesn't have anything to do with the method showData. showData is invoked by pressing a button on form1.

Thanks.

Regards,

Carlos
 
Hi Chip H.,

I looked at your replies but I am not sure how can I apply them to the problem I'm having. Let me try to express myself better:

I have a form called Form1 with a single control: a textBox called textBox1.

I added a class to that project called Class1. The code for Class1 is:

using System;
using System.Collections.Generic;
using System.Text;

namespace useFormsControlsFromAnotherForm
{
class Class1
{
public void ChangeText()
{
Form1.TextBox1.Text = "Hi There";
}

}
}

I can't change the text of TextBox1 using the ChangeText method.

Regards,

Carlos

 
Hi Carlos,

You have run into a situation where you need to communicate between instances of forms and objects to change their properties.

If this is a small project, then the simple solution would be to "Register" your form with your class.

namespace useFormsControlsFromAnotherForm
{
class Class1
{
private Form1 registeredForm;

public void RegisterMyForm(Form1 frm)
{
registeredForm = frm;
}


public void ChangeText()
{
registeredForm.textbox1.Text = "Hi There";
}

}
}

Your textbox will have to be public in order to do this. Instead of a public textbox, you might just want to make a public method SetText1Text(string text)

public void SetText1Text(string text)
{
this.textbox1.Text = text;
}

This is usually the preferred method.


If this is a larger project, you will want to familiarize yourself with the Model - View - Controller design pattern. This will let you set properties of many objects through one common place (the controller)

Happy Googling!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top