Manipulating form text across classes

2019-09-10 10:25发布

问题:

I'm having a humdinger of a time getting this to work, and I feel like it's so simple...

I have 2 classes, form1.cs and logic.cs

On form1, I have a private variable "output", with public property Output that I can set the value. I also have a public method to set the contents of textbox1.Text (keeping textbox1 private).

namespace myNamespace
{
    public partial class Form1 : Form
    {
        private string output;

        public string Output
        {
            get { return output; }
            set
            {
                if (!String.IsNullOrEmpty(value))
                    output += value;
            }
        }

        public void SetTextbox1(string value)
        {
            textbox1.Text = value;
        }
    }
}

On logic, I have instances where I'm trying to change the variable on form1 to update the textbox1

namespace myNamespace
{
    class logic
    {
        public void Info(string imagePath, string mountDir)
        {
            mountDir = "C:\\mount"

            try
            {
                DismImageInfoCollection imageInfo = DismApi.GetImageInfo(mountDir)
                form1.Output = imageInfo.ToString();
                form1.SetTxtOutput(form1.Output);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

I'm getting error messages in the last 2 lines of try that say:

An object reference is required for the non-static field, method, or property 'form1.Output'

If I change Output, SetTxtOutput(), and output to static, it complains because textbox1 isn't static as well.

What is the proper way of manipulating textbox Text values across classes without setting the textbox to public and manipulating it directly?

回答1:

You need to actually pass the form1 object to the logic class I.e.

 //default constructor
 Logic(form1 Form)
 {
     Form.output;
 }

The reason that you are getting the error is because winforms creates a new class for each form, and to access elements of a class without instantiating it those elements need to have the static keyword.

As a side note if you just create a new instance of form1 (form1 form = new form1()) this creates a new instance of the form and not the displayed form.