Written by WATYF on Thursday, 25 September 2008 (10761 hits)
Category: .NET Programming
Whenever I have trouble finding an example on the internet of how to do something in .NET, I usually throw the solution up here so that all of the other poor, unfortunate souls (like myself) have a little better chance of finding it in the future.
Today's solution is a quick one. It involves applying a format to a databound textbox. I recently delved into the wonderful would of Visual Studio Data Binding. I have always done all of my db calls manually in my code. But on this project, I was looking to basically replace an app that I wrote years ago in Access (which consisted of several forms bound to database tables), and the forms had a ridiculously large amount of fields on them (in the hundreds, all told)... so I didn't feel like coding all that myself.
As a result, I started learning how to use the "wizards" in VS.NET to add connections to a database. I created a Data Connection, a Data Source, a DataSet, dragged some controls on to my form (which created a BindingSource and TableAdapter)... and voila... my form is connected to a database.
But this simplicity is not without its problems....
The main problem with this approach (much like every other "automated" approach) is less control. The more you let the software (in this case VS.NET) do for you, the less control you have over how things happen.
So, when it came time to apply a format (in this case, Currency) to a few of those textboxes, I hit a wall. If I was setting the contents of the textbox using the ".Text" property, I could just use myTextbox.Text = Format(dValue, "$#.00)... or something to that effect. If I was creating the databinds myself, I could use Binding.Format (although, the idea of having to add Events for every textbox that needs to be formatted seems really lame to me). But since I'm doing all of the databinding using the wizards, I can't mess with the code that actually sets up those textboxes... I have to find a way to change things after the fact.
Fortunately, I stumbled on the way to do this... and it's really easy (no Events required). I'm just surprised that I never found an example of this method in any of the searching I did. But now it's on the internet for eternal posterity... so enjoy.
myTextBox.DataBindings.Item(0).FormatString = "$#.00"