2010-03-24 101 views
0

我有一个ASP ListView,并有一个非常简单的要求,以格式化显示数字用逗号(12,123),而他们需要绑定到数据库而不格式化(12123)。我正在使用一个标准的设置 - 使用Bind()连接数据源的ListView。ASP ListView - Eval()格式化的数字,绑定()为未格式化?

我从一些旧的代码转换,所以我不使用ASP.NET控件,只是表单输入...但我不认为它很重要的是:

<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> 

在上面的例子,NUMSTR是一个数字,但作为字符串存储在SqlServer 2008数据库中。我还使用ItemTemplate作为读取和编辑模板,以保存重复的HTML。在这个例子中,我只能得到未格式化的数字。如果我将字段转换为整数(通过SELECT)并使用格式字符串(如Bind("NUMSTR", "{0:###,###}")),它会将格式化的数字写入数据库,然后在尝试再次读取时失败(无法使用逗号)。

有没有优雅/简单的解决方案呢?它是那么容易得到的双向绑定去,我认为必须有一个方法可以轻松地格式化的东西,以及...

哦,我试图避免标准ItemTemplateEditItemTemplate方法,仅仅是为了达到这个标准所需的标准量。

谢谢!

+0

我结束了刚刚剥从NewValues集合在ListView ItemUpdating事件逗号,并在ItemDataBound事件中添加逗号。任何其他方式以干净的方式做到这一点? – chucknelson 2010-03-24 21:01:39

回答

1

正如我在上面的评论中所看到的,我最终从ListView ItemUpdating事件中的NewValues集合中删除了逗号,并在ItemDataBound事件中添加了逗号。

如果还有其他方法可以用干净的方式做到这一点,我很感兴趣!

代码在VB.NET,注释语法做成与计算器的高亮兼容:

Protected Sub myListView_OnItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles myListView.ItemDataBound 
    Dim intNumber As Integer 
    For Each c As Control In e.Item.Controls 
     If TypeOf c Is TextBox Then /*ASP textbox controls*/ 
      Dim numberText As TextBox 
      numberText = DirectCast(c, TextBox) 
      If Integer.TryParse(numberText.Text, intNumber) Then /*If the text can be parsed, format it*/ 
       numberText.Text = String.Format("{0:###,##0}", intNumber) 
     End If 
    Next 
End Sub 

Protected Sub myListView_OnItemUpdating(ByVal sender As Object, ByVal e As ListViewUpdateEventArgs) Handles myListView.ItemUpdating 
    Dim cleanNumber As String 
    Dim intNumber As Integer 
    For Each key As String In e.NewValues.Keys 
     cleanNumber = e.NewValues(key).ToString().Replace(",", Nothing) /*Remove all commas*/ 
     If Integer.TryParse(cleanNumber, intNumber) Then /*If the text can be parsed, format it*/ 
      e.NewValues(key) = intNumber.ToString() 
     End If 
    Next 
End Sub 
0

不能使用<%#绑定(“表达式”[,“格式”])%>风格? 所以在你的情况下,设计一个格式字符串(我认为它应该是“#,###”),并且ASP.NET将能够在输入和输出上格式化字符串。

+0

使用该方法也会导致格式化值写入数据库,这不是所需的功能。我需要它显示为格式化,写入为未格式化。感谢您的意见,但:) – chucknelson 2010-04-02 12:33:14