I want to retrieve the designer-assigned values of controls, e.g. when I designed a TextBox
with the .Text
"Hello World", then change the .Text
during runtime: How can I retrieve the String "Hello World" again during runtime?
My thoughts so far: I can write a set-up routine and assign these "default" values in there alone, and call that method again when ever I want to reset the values. Cons:
- Not as flexible (No way of resetting individual Controls)
- would need to write a routine for each implementation
- missing out on the convenience of just setting the values once in the designer
I would really like a static method/extension which would enable me to plug in my Control and get the values assigned to it within my class designer.
I started trying to implement an extension within my extension library, where I create a new instance of the main Form Class and grab the value from there - but that approach has obvious disadvantages:
- The Form Class may have different constructor signatures, like string[] args
for applications with console arguments; creating instances of unknown signatures isn't trivial or a good idea in general
- It's a heavy weight approach; depending on the complexity of the project, you might not want to create piles of instances every time you want to get a Control's designer-assigned value.
- This would execute what ever code is in the constructor
So I'm really hoping I can use Reflection
or something similar to get to the designer-assigned values.
But I have no idea how to go about looking for that; googling things like "visual .net get designer default control value" yielded no relevant results.
Can somebody point me in the right direction?
My test extension method currently looks something like this:
public static string getDefaultText(this Control c)
{
Form mainForm = Form.ActiveForm; // just a quick easy way to test this
Type t = mainForm.GetType();
var f = Activator.CreateInstance(t);
Control a = ((Form)f).Controls[c.Name]; // unfortunately, .Controls only contains direct children, not all descendants; recursive searching would be needed
return a.Text;
}
and works for what it is, which is to say a proof of concept of a bad approach :/
Aucun commentaire:
Enregistrer un commentaire