Two-way formatted data binding in ASP.NET

Security Briefs

Syndication

Two way data binding in ASP.NET is easy, just use the Bind expression and data will flow between your web controls and your data source flawlessly. Until that is, you try to use a format string:

Bind("AmountCharged", "{0:C}")

While this displays just as you'd expect (e.g., $200), it doesn't do so well when you submit an edit that includes the same value ($200):

Input string was not in a correct format.

I searched around and didn't find much in the way of a clean solution, but I did solve the problem with just a few lines of code. The trick is to handle the data-bound control's Updating event. Since I was working with a GridView, my solution looked a bit like this:

<asp:GridView DataSourceID='myDataSource'
              OnRowUpdating='FixFormatting'
              AutoGenerateColumns='false'
              CellPadding="3" ...>

Notice the OnRowUpdating handler that I've installed in my grid view. That code looks like this:

protected void FixFormatting(object sender, GridViewUpdateEventArgs args)
{
    decimal amountPaid = ParseDecimal((string)args.NewValues["AmountPaid"]);
    args.NewValues["AmountPaid"] = amountPaid;
}

When you handle this event, you're given a dictionary of old and new values, which appear to come directly from the controls (in my case, a TextBox was used to gather the updated data AmountPaid, so the type of object that I found in NewValues["AmountPaid"] was a string. I wrote a little helper method called ParseDecimal that parses a string into a decimal value, allowing currency characters, decimal points, and thousands separators. I also allowed a blank value to indicate zero:

public static decimal ParseDecimal(string value)
{
    if (string.IsNullOrEmpty(value))
        return 0;
    return Decimal.Parse(value,
        NumberStyles.AllowThousands |
        NumberStyles.AllowDecimalPoint |
        NumberStyles.AllowCurrencySymbol,
        CultureInfo.InstalledUICulture);
}

This solved the problem quite nicely. Now two-way binding works with formatted data.


Posted Aug 15 2008, 01:22 PM by keith-brown
Filed under: ,

Comments

YESChandana -Blog wrote My favorite links from the 3rd week of August 2008
on 08-17-2008 6:53 AM

My favorite links from the 3rd week of August 2008

Kostenloser WEB Space wrote Kostenloser WEB Space
on 12-13-2008 7:00 AM

Andere haben Werbebanner in gratis Web Spaces vorgesehen.