I'm trying to access a control's text property from program.cs and it says that it is inaccessible due to protected level. How can I fix this please?
Asked
Active
Viewed 5.8k times
27
-
1What are you trying to accomplish? – Daniel A. White Nov 16 '09 at 15:31
-
2FWIW, a question like this means you are going down a path of very tight coupling (accessing myForm.myControl.Text outside of myForm's code is a bad idea). – Austin Salonen Nov 16 '09 at 15:41
-
is this a bad idea only because it can be insecure? or are there other reasons too? – jay_t55 Nov 16 '09 at 18:13
-
It's a bad idea because it exposes implementation details more than it needs to. What if you, in the future, decide to replace the text box with a drop-down list of choices? – erikkallen Nov 16 '09 at 20:31
-
hmmm point taken. thanks for clearing that up arikkallen :) – jay_t55 Nov 17 '09 at 04:03
4 Answers
36
This is the default property for controls and can be solved by:
- Going into Design-View for the Form that contains the specified Control
- Then changing the Control's Modifiers property to Public or Internal.

Peter Duniho
- 68,759
- 7
- 102
- 136

jay_t55
- 11,362
- 28
- 103
- 174
-
4Note: just to emphasize as this seems to have been very unclear by the asker, this is the *control's instance itself* that's protected (i.e., the variable holding the control), not the *`.Text` property*, which is public. – Abel Nov 16 '09 at 17:35
-
It is worth pointing out for SEO that this works in xamarin XAML as well – lucidbrot Apr 12 '19 at 08:12
-
Tried this for textbox and got the error "An object reference is required for the nonstatic field, method, or property 'textbox' – SimonKravis Aug 11 '23 at 23:42
6
Control Protection level Resolved
Go to designer file search control By ID e.g txtModel change protected modifier to public modifier

Asad
- 91
- 2
- 5
-
3This is not a good idea. Better is to access value of control thru property of class, where control is used. – eridanix Sep 22 '12 at 21:25
-
@asad It is not a good idea to access the child controls directly because you cannot change/maintain/modify the child without updating the grandparent. This is encapsulation. – Brian Leeming Jul 19 '16 at 13:36
3
Use x:FieldModifier="public"
e.g.
<TextBlock x:FieldModifier="public" x:Name="AccessibleTextBlock" />
as explained here: Modifying XAML named field visibility
In my case, I put UserControl in another DLL. WPF’s convention is to set all named fields as internal
by default. Using the x:FieldModifier="public"
has solved the issue.

Michael G
- 129
- 10
1
The concept behind is the protection level. As we have studied in Object Oriented Paradigm keep your class members variables private and set or get it from Property.Thats why it is not a good approach

Asad
- 91
- 2
- 5