Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...