代码之家  ›  专栏  ›  技术社区  ›  Bob Kaufman

ASP.NET网格视图:如何在编辑模式下控制列的格式?

  •  1
  • Bob Kaufman  · 技术社区  · 15 年前

    给出以下内容 GridView 以下内容:

    <asp:GridView runat="server" ID="GridMenuItemAttributes" DataKeyNames="MenuItemAttributeID" AutoGenerateColumns="false" 
            OnRowCommand="GridMenuItemAttributes_RowCommand" DataSourceID="DSMenuItemAttributes" OnRowEditing="GridMenuItemAttributes_RowEditing" >
    <Columns>
        <asp:BoundField HeaderText="Description" DataField="DisplayName" />
        <asp:BoundField HeaderText="Price" DataField="Price" DataFormatString="{0:F2}" />
        <asp:CommandField ShowEditButton="true" ShowDeleteButton="true"
                EditText="Edit" DeleteText="Delete" />
    </Columns>
    </asp:GridView>
    

    这个 Price 在查看行时,字段的格式正确,有两个小数位,但在编辑行时更改为四个小数位。我尝试了不同的格式(例如“c”,“0.00”),并附加了以下OnRowEditting处理程序:

    protected void GridMenuItemAttributes_RowEditing( object sender, GridViewEditEventArgs e )
    {
        int menuItemAttributeID = Convert.ToInt32( GridMenuItemAttributes.DataKeys[ e.NewEditIndex ].Value );
    
        if ( ! String.IsNullOrEmpty( GridMenuItemAttributes.Rows[ e.NewEditIndex ].Cells[ 1 ].Text ) )
        {
            String theValue = GridMenuItemAttributes.Rows[ e.NewEditIndex ].Cells[ 1 ].Text;
            GridMenuItemAttributes.Rows[ e.NewEditIndex ].Cells[ 1 ].Text = String.Format( "{0:0.00}", Convert.ToDouble( theValue ) );
        }
    }
    

    一切都无济于事。客户坚持,并且合理地说,在编辑单元格时,值应该以两个小数位显示。

    1 回复  |  直到 15 年前
        1
  •  3
  •   Bob Kaufman    15 年前

    默认情况下,仅当包含 BoundField 对象处于只读模式。要在编辑模式下将格式字符串应用于字段值,请设置 ApplyFormatInEditMode 属性设置为true。

    来自: MSDN DataFormatString

    希望有所帮助