Sunday, July 18, 2004

MSDN Masked Edit Control C# Sample Doesn't Work Too Well

I recently used the Masked Edit Control using .NET Framework Regular Expressions with C# sample as the base class for a Textbox control that automatically added data entry masking based on the data type of the column that it was databound to. To be fair to the sample's author, the Masked Edit Control is advertised as only forming the "basis" of a masked edit control, but doesn't go into a lot of detail about what parts of the sample need further development to arrive at a commercial-strength offering.


One part of the sample that is definitely lacking is the way the key press event arguments are used to construct a representation of the contents of the Textbox should the key press be allowed. The sample assumes the user is entering characters in order, doesn't used delete or backspace, doesn't use the clipboard or undo operations, and doesn't highlight any text. For the application I was developing, these assumption were too limiting. and I wrote a small method that added handling for text highlighting, backspaces and insertion at any location in the textbox. The method takes the original Text of the TextBox(this.Text), the new character (e.KeyCode), the caret position (this.SelectionStart), and the length of text selected (this.SelectionLength).

protected string GetSting(string originalString, char newChar, int startSelection, int selectionLength)
{
 //TODO: undo, delete, cut, copy, paste
 if (Char.IsControl(newChar) && newChar != '\b')
  return originalString; //give up - catch any errors on exit

 if (newChar == '\b') //backspace
 {
  if (selectionLength == 0)//lose char left of selection point (if there is any)
  {
   if (startSelection == 0)
   {
    return originalString;
   }
   else
   {
    string s = originalString.Substring(0, startSelection - 1) +
     originalString.Substring(startSelection);
    return s;
   }
  }
  else//lose selected chars
  {
   string s = originalString.Substring(0, startSelection) +
    originalString.Substring(startSelection + selectionLength);
   return s;
  }
 }
 else
 {
  if (selectionLength == 0)//insert
  {
   string s = originalString.Substring(0, startSelection) +
    newChar.ToString() +
    (startSelection < originalString.Length ? originalString.Substring(startSelection) : "");
   return s;
  }
  else//lose highlighted chars
  {
   string s = originalString.Substring(0, startSelection) +
    newChar.ToString() +
    originalString.Substring(startSelection + selectionLength);
   return s;
  }
 }
}


The method doesn't handle delete (which doesn't raise a KeyPress event), and clipboard operations. Moving to KeyUp/ KeyDown event handling would allow the full range of input operations to be caught, but is about two orders of magnitude more complex. If you are using this sample, these enhancements will cover about 80% of the masked edit functionality ...

0 Comments:

Post a Comment

<< Home