display something in textBox of my form

C

Claudia Fong

Hi,

In my form I have a textbox.

I have a class where I have a method to add two number.

Can I define in the method of my class to display the result in the
textbox of my form?

I the method is define insidemy form I know how to do it...

public int AddIntegers(int x, int y)
{

result = (x + y);
textBox1.text = result;

}

Cheers!

Claudi
 
M

Morten Wennevik [C# MVP]

Hi Claudia,

Yes you can have the class update the TextBox, but the method (AddIntegers) need a reference to the TextBox. The reference can be passed as a parameter of the method

public int AddIntegers(int x, int y, TextBox textBox1)
{
result = (x + y);
textBox1.text = result;
}

Or pass a referenec to the TextBox or the Form when creating an instanceof the class


public class MyClass
{
private MyForm parent;

public MyClass(MyForm myForm)
{
parent = myForm;
}

public void AddIntegers(int x, int y)
{
result = (x + y);
parent.textBox1.text = result;
// textBox1 needs to be public
}
}

However, you should try to avoid having the class update a Control directly like this. Try creating a property on the Form that updates the TextBox

public class MyClass
{
private MyForm parent;

public MyClass(MyForm myForm)
{
parent = myForm;
}

public void AddIntegers(int x, int y)
{
result = (x + y);
parent.SomeText = result;
}
}

public class MyForm
{
private TextBox textBox1;

public string SomeText
{
get{ return textBox1.Text; }
set{ textBox1.Text = value; }
}

public MyForm
{
MyClass myClass = new MyClass(this);
myClass.AddIntegers(2, 4);
}
}
 

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