Tuesday, October 21, 2008

ASP.NET 2.0 useful formatting tips

This post applies to ASP.NET 2.0, using VB.NET. It contains some useful tips on dealing with data binding syntax and formatting of data.

Conditional boolean field formatting in a GridView
<ItemTemplate>
<asp:Label ID="Label3"
runat="server"
Text='<%# IIf(CBool(DataBinder.Eval(Container.DataItem,"hasPassedFlag")) = true, "Pass","Fail" )%>'>
</asp:Label>
</ItemTemplate>
Parsing decimal numbers before SqlDataSource fires update/insert

Sometimes, the UI shows a number in ###.## format but the underlying culture info has ###,## for the decimal format. If left untouched, entering a ###.## would get interpreted as a much larger number in the context of the culture info that expects ###,## decimals.

To avoid problems, intercept the inserting/updating event on the form view and manipulate the decimal value there, setting the appropriate value into the SqlDataSource parameters.

Sample definition of the SqlDataSource with its parameters:
<asp:SqlDataSource runat="server" ... >
<UpdateParameters>
<asp:FormParameter
Type="Decimal"
FormField="fldAmount" Name="fldAmount" />
</UpdateParameters>
... // similar for InsertParameters
</asp:SqlDataSource>
FormView uses the above SqlDataSource as the DataSourceID and contains a TextBox bound to the fldAmount:
<asp:TextBox Text='<%# Bind("fldAmount") %>' ID="fldAmount" runat="server"></asp:TextBox>
In the code behind, handle the ItemInserting/ItemUpdating events of the FormView. First, deal with ItemInserting:
Protected Sub form1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles form1.ItemInserting
Dim tmp As Decimal
tmp = Decimal.Parse(e.Values.Item("fldAmount"), System.Globalization.CultureInfo.InvariantCulture)
e.Values.Item("fldAmount") = tmp
End Sub
Similarly, ItemUpdating (notice the e.NewValues)
Protected Sub form1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewUpdateEventArgs) Handles form1.ItemUpdating
Dim tmp As Decimal
tmp = Decimal.Parse(e.NewValues.Item("fldAmount"), System.Globalization.CultureInfo.InvariantCulture)
e.NewValues.Item("fldAmount") = tmp
End Sub
That should do the trick. The form value for fldAmount would get appropriately parsed and then via data-binding that's already in place would get properly updated in the database.

3 comments:

Rem said...

Your blog is very nice...
visit my blog asp.net example

Rem said...

Your blog is very nice...
visit my blog asp.net example

Jen said...

The blog is helpfull...
visit also asp.net [c#]