Wednesday, March 21, 2012

Switch from code control to property control

In Delphi, we can control an Edit’s length and what can go in in the event KeyPress, for example, I have found my old code (code I have inherited from somebody else) do such things like this:

//Control only numbers can go in

if not (CharInSet(Key , ['0'..'9', #8])) then
  key := #0;

//Control the length

if (Length(edtFileNumber.Text) > 8) and (key <> #8) then
  key := #0;

But there are easier ways, they can be accomplished by the component’s properties (confirmed in Delphi XE).

For example, the property TLabeledEdit.MaxLength can control the length of editing text.

The property TLabledEdit.NumbersOnly can control only numbers can go in.

 

(Please note that I have found a lot places using above code-control pattern in my old code but I have not change all of them to property control, the reason will be worth another topic, long in short, that is about risk control while changing working code)

No comments:

Post a Comment