繁体   English   中英

VB.NET如何将十进制格式应用于Gridview中的特定列?

[英]VB.NET How do I apply decimal formatting to a specific column in a Gridview?

如何将十进制格式应用于Gridview中的特定列?

例如,正在从SQL填充83.7837837837838,如何将其转换为83.8。

我只想将其应用于一列,因为其他列是整数,所以这不是必需的。

一种方法是使用DataFormatString属性。 例如:

 <asp:GridView ID="GridView1" runat="server" 
    AutoGenerateColumns="False" 
    DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
    <Columns>
        <asp:BoundField DataField="ListPrice" 
            HeaderText="ListPrice" 
            SortExpression="ListPrice"
            DataFormatString="{0:F1}" />
    </Columns>
</asp:GridView>

你也可以使用RowDataBound控制你:

protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        // assuming you are using BoundFields and
        // the column which you want to format is the first
        // if you are using TemplateFields use e.Row.FindControl("ControlID") to find your controls
        var row = (DataRowView) e.Row.DataItem;
        decimal price = (decimal)row["ListPrice"];
        e.Row.Cells[0].Text = price.ToString("F1");
    }
}

编辑:这里的VB.NET版本:

Protected Sub GridView1_RowDataBound(sender As [Object], e As GridViewRowEventArgs) Handles GridView1.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        ' assuming you are using BoundFields and                                                   '
        ' the column which you want to format is the first                                         '
        ' if you are using TemplateFields use e.Row.FindControl("ControlID") to find your controls '
        Dim row = DirectCast(e.Row.DataItem, DataRowView)
        Dim price As Decimal = CDec(row("ListPrice"))
        e.Row.Cells(0).Text = price.ToString("F1")
    End If
End Sub

您只需要使用BoundField.DataFormatString属性,为了解决您的问题并获得适当的知识,请检查此Microsoft链接

希望对你有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM