Get and Set Properties using .NET Reflection
Introduction
I would like to set the text value on a textbox control. It sounds easy enough. First, I would like to create a textbox web control then I would like to access one of its properties “Text” and set the text to “Hello World”. Well what do you need to do to write your code in a generic way so you are can abstraction of the fact that the web control is actually a text box, it could be any web control.
We will visit different ways to be able to this.
Sample 1
Let’s start with the basics. I want to create a dynamic control a text box. Next, I need to set statically the Text property and as a last step the control is added to the control tree on the page.
On the mark up page we have a place holder control. We will add controls dynamically to the place holder.
On code-behind, we will define a method that will create our dynamic controls:
Sample 2
The next step is actually to use reflection to be able to set the value of the property dynamically. Make sure the namespace is added one your code-behind file
Sample 3
If we intend to update looping throw the properties then we could proceed as the following.
Conclusion
We learnt how to set dynamically properties using different techniques.
On our next chapter, we will learn how to set sub properties for example the Size property of a TextBox control has sub properties like Unit and UnitType classes.
If we also stress our attention to a technique I developed to set the FontInfo which is a sealed class. This will allow us to define properties like the font name, bold, underline, strikeout…
Thanks for reading. I hope that this article helped you out.