comboBox2 (or any particular form item) is inaccessible due to its protection level

余生长醉 提交于 2021-02-17 02:06:13

问题


I am working on a win-forms. Currently working on the .cs class called HM_Settings.cs which works in conjunction with HM_SettingsForm.

I am trying to access the variables of the form items, by declaring these global variables

    public Brush backgroundColor;
    public Brush textColor;
    public double timeOffset;
    public double dateOffset;
    public string title;
    public bool showTitle;
    public bool showText;

    public HM_SettingsForm hmf = new HM_SettingsForm();

I am trying to use the form's variables by assigning them to the global variables, like so:

title = hmf.textBox1.Text;
showTitle = hmf.checkBox1.Checked;
showText = hmf.checkBox2.Checked;

The above should work. However, I am struck with this error, telling me it is inaccessible due to its protection level.

enter image description here

As a result, I tried changing certain values from private to public, but to no avail. What could I do?


回答1:


The controls defined inside the HM_SettingsForm class using the WinForms Designer are private by default, so it is not possible to reach their property from an external class.

You could change the property Modifiers using the WinForms Designer or directly modifying the HM_SettingsForm.Designer.cs file and set it to public, but I don't recommend to resolve the problem in this way.
Leaving open access to the internal controls of a form could lead to problems in future.
(A spectacular breach of the encapsulation rule of OOP)

Instead I suggest to create, inside the HM_SettingsForm class, some public properties (with only the get accessor) that returns the internal values of these controls.
(You have also the benefit to add your own custom code if the need arises)

For example, you could write this property inside the HM_SettingsForm class

public class HM_SettingsForm:Form
{
     // Of course, here a more meaningful name 
     // is a must for future readers of your code
     public string ComboBox2Text
     {
         get{return this.combobox2.Text;}
     }
}

As a side note, not actually related to the current question but....
It seems an error to return a string and assign that value to a Brush object.




回答2:


Your controls are either private or protected. View the code behind file of your form and create properties to access the values. This will allow you to access the data without accessing or modifying the accessibility of the controls directly.

public string ComboBox2Text
{
    get
    {
        return comboBox2.Text;
    }
}

Then, in your first form, do

backgroundColor = hmf.ComboBox2Text;


来源:https://stackoverflow.com/questions/21270188/combobox2-or-any-particular-form-item-is-inaccessible-due-to-its-protection-le

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!