2010-03-24 112 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