I created a class that I called MaskedHexTextBox which inherits from MaskedTetxBox to make it accept only HEX values. Anyway, I need to do the following:
- Give PromptChar a default value of '0' in MaskedHexTextBox, and still be able to change it in the form design
- Give Mask a default value of "\0xAAAA", and still be able to change it in the form design as well
- Use Mask.Length as the default value of MaxLength, I need to use in some calcs, and if I change the Mask after I place the control on the form, I still get the correct Mask length
In general, how can I set a default values for Mask and PromtChar, is there a specific event that I can use to give these properties default values once the control is placed on the form?
I used the class constructor to do this:
public MaskedHexTextBox()
{
Mask = "\\0xAAAA";
PromptChar = '0';
MaxLength = Mask.Replace("\\", string.Empty).Length;
}
in the Form_load event, I still see that the value for MaxLength is 32767
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show(maskedHexTextBox1.MaxLength.ToString());
}
Another issue, suppose that MaxLength was correct, how can I ensure that if the mask is changed from the form design that MaxLength is updated?
About
Mask
andPromptChar
properties, if you want the designer to use your custom default values instead of the base ones, then you have to associate them through some helper class (like aDesigner
that overridesPreFilterProperties
) or to hide the base properties declaring new ones with the same names, like:For the
MaxLength
property, theoretically you should override it, but the classMaskedTextBox
provides an empty set accessor that never change the underlyingTextBoxBase.maxLength
field, so you cannot change through the base property.You can however try through Reflection, eventually improving your
Mask
property:If you also want the
MaxLength
property to be visible from the designer, you can add:UPDATE_20141127 (A) To address the fact that TextBoxBase.MaxLength seems to not change, you can override OnHandleCreated:
UPDATE_20141127 (B) At the following link you can find my (working) test project, containing a minimal MaskedTextBox derived class and a form to display it, along with a button to change the Mask and check MaxLength value. Test project
At this other link you can find an already compiled exe for the previous project. Test exe
Regards, Daniele.