I asked a question a couple of days ago about populating a listbox on a form from a class. It works and was great! However I now want to do the same with a textbox or a label. The answer from that question is below:
What you are doing is creating a new instance of the form - I presume you are trying to add items in a listbox on an existing form?
If so do this.
Create a function on the form with the listbox like:
public void addItemToListBox(string item) { listBox1.Items.Add(item); }
Then, in the class (remember to add the using System.Windows.Forms reference)
public void doStuff() { //Change Form1 to whatever your form is called foreach (Form frm in Application.OpenForms) { if (frm.GetType() == typeof(Form1)) { Form1 frmTemp = (Form1)frm; frmTemp.addItemToListBox("blah"); } } }
This works well. Now I want to do the same with a textbox. I was wondering if someone could explain or if someone has a link on this?
I have a form and a class. The form makes a new instance of the class and initiates a method in the class, say a maths equation 4+4; I want the answer, "8" to then be shown in a textbox or label on form1, from the method in the class.
What you are describing, with your edit, is a model in which your Form
uses another class. The class that is being used should have no knowledge of the Form
, it's controls, or how the result of its calculation could possibly be used.
Your other class shouldn't find the form, it shouldn't call any methods or fields of the form, or anything. What it should do is just return a value:
public class OtherClass
{
public int Add(int first, int second)
{
return first + second;
}
}
Then the form can do something like this:
private void button1_Click(object sender, EventArgs e)
{
//create an instance of the other class
OtherClass other = new OtherClass();
//call it's add method, and then use the result to set the textbox's text
textbox1.Text = other.Add(4, 4).ToString();
}
The other class should be responsible for doing the calculations, creating a result, but not updating the user interface based on those results. All of the user interface logic should be contained in the Form
class.