As mentioned in my previous post it’s been quite a while since I last had the fortune to work on a web application. Today I discovered another gotcha for young players in the web world when trying to set the MaxLength property of a TextBox control. Normally this works fine, but if you combine this with settinig the style to MultiLine the world changes.
What’s going on here is that the TextBox control is rendered in 2 ways. Normally it’s rendered as an input control, which allows the max length property to work as intended. However, in multiline mode it renders as a TextArea control, which doesn’t implement the MaxLength property! No good for those of us attempting to limit our user input lengths…
So how to fix it? After spending some time playing with validation controls combined with update panels I decided it just wasn’t going to happen unless I started writing some script. Now I normally shudder at the possibility of working with script, but I really have to say that it’s been quite pleasent this time around.
I downloaded the ASP.Net AJAX control toolkit and took a look around to see how these extenders are put together. Basically they consist of a behaviour (client script), an extender (server side code), and a designer (to allow for use in the IDE). It seems that with the toolkit, most of the hard work wiring things together is done for you. All you really need to do is define any public properties you’d like to implement in your server side code, wire them up using the provided Get and Set methods from the toolkit then get to coding your behaviour in the script files.
For my particular problem there was already a number of solutions out there, on CodeProject and also on various blogs. I’ve ended up with a nice mesh of a few solutions that involves filtering the key down event to check the user input once the control reaches the max length then allows or denies the key press events to continue firing. It’s not quite in the wild yet, but I’m hoping it will survive the rigours of beta use and prove a worthy addition to our internal toolset.
I’m also putting together an article on how I went about writing the extender for those interested. So if that’s you – watch this space 🙂