ASP ListView - Eval() as formatted number, Bind() as unformatted?

Posted by chucknelson on Stack Overflow See other posts from Stack Overflow or by chucknelson
Published on 2010-03-24T18:45:23Z Indexed on 2010/04/02 12:43 UTC
Read the original article Hit count: 205

Filed under:
|
|

I have an ASP ListView, and have a very simple requirement to display numbers as formatted w/ a comma (12,123), while they need to bind to the database without formatting (12123). I am using a standard setup - ListView with a datasource attached, using Bind().

I converted from some older code, so I'm not using ASP.NET controls, just form inputs...but I don't think it matters for this:

<asp:SqlDataSource ID="MySqlDataSource" runat="server" 
  ConnectionString='<%$ ConnectionStrings:ConnectionString1 %>' 
  SelectCommand="SELECT NUMSTR FROM MY_TABLE WHERE ID = @ID" 
  UpdateCommand= "UPDATE MY_TABLE SET NUMSTR = @NUMSTR WHERE ID = @ID">
</asp:SqlDataSource>

<asp:ListView ID="MyListView" runat="server" DataSourceID="MySqlDataSource">
  <LayoutTemplate>
    <div id="itemplaceholder" runat="server"></div>
  </LayoutTemplate>
  <ItemTemplate>
    <input type="text" name="NUMSTR" ID="NUMSTR" 
      runat="server" value='<%#Bind("NUMSTR")%>' />
    <asp:Button ID="UpdateButton" runat="server" Text="Update" Commandname="Update" />  
  </ItemTemplate>
</asp:ListView>

In the example above, NUMSTR is a number, but stored as a string in a SqlServer 2008 database. I'm also using the ItemTemplate as read and edit templates, to save on duplicate HTML. In the example, I only get the unformatted number. If I convert the field to an integer (via the SELECT) and use a format string like Bind("NUMSTR", "{0:###,###}"), it writes the formatted number to the database, and then fails when it tries to read it again (can't convert with the comma in there).

Is there any elegant/simple solution to this? It's so easy to get the two-way binding going, and I would think there has to be a way to easily format things as well...

Oh, and I'm trying to avoid the standard ItemTemplate and EditItemTemplate approach, just for sheer amount of markup required for that.

Thanks!

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about databinding