I'm working on a C# program, and right now I have one Form
and a couple of classes. I would like to be able to access some of the Form
controls (such as a TextBox
) from my class. When I try to change the text in the TextBox
from my class I get the following error:
An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog'
How can I access methods and controls that are in Form1.cs
from one of my classes?
You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.
If you actually wanted to access the form components directly from a class (which you don't) you would use the variable that instantiates your form.
Depending on which way you want to go you'd be better of either sending the text of a control or whatever to a method in your classes eg
public void DoSomethingWithText(string formText)
{
// do something text in here
}
or exposing properties on your form class and setting the form text in there - eg
string SomeProperty
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}
Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestClass test = new TestClass();
test.ModifyText(textBox1);
}
}
public class TestClass
{
public void ModifyText(TextBox textBox)
{
textBox.Text = "New text";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With