如何在网格视图中绑定项目

本文关键字:绑定 项目 视图 网格 | 更新日期: 2023-09-27 17:59:14

这是一个由两部分组成的问题,我使用数据集和网格视图。数据集是通过查询数据库来填充的,之后进行一些计算并添加到数据集中。完成所有计算后,数据集将绑定到网格视图。它看起来像这样。

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        CellPadding="4" ForeColor="#333333" GridLines="None" Width="100%"  CssClass="tableText" >
        <AlternatingRowStyle BackColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F5F7FB" />
        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
        <SortedDescendingCellStyle BackColor="#E9EBEF" />
        <SortedDescendingHeaderStyle BackColor="#4870BE" />
        <Columns>
        <asp:BoundField DataField="INV_GP" HeaderText="INV GP" />
        <asp:BoundField DataField="SORG_GP" HeaderText="SORD GP" />
        <asp:BoundField DataField="SRTN_GP" HeaderText="SRTN GP" />
        <asp:BoundField DataField="EXPEND" HeaderText="EXPEND" />
        <asp:BoundField DataField="TARGET" HeaderText="TARGET" />
        <asp:BoundField DataField="PERC_OF_TARGET" HeaderText="%" />
        <asp:BoundField DataField="M_PERC" HeaderText="M%" />
        <asp:BoundField DataField="100NEED" HeaderText="NEED FOR 100%" />
        </Columns>
    </asp:GridView>

以下是我想做的事情:

  1. 正如您所看到的,其中的列有%个值,但数据集只有数字。如何在网格视图中的数字旁边显示%?

  2. 我希望能够添加某种条件语句,以便能够以不同的颜色显示文本。例如,在m%中,如果任何值小于50%,我希望文本显示为红色。

如何在网格视图中绑定项目

使用TemplateField而不是BoundField,并为内容分配一个类来定义颜色。

CSS

<style type="text/css">
.MoreThanFifty { color: green; }
.FiftyOrLess { color: red; }
</style>

ASP.NET

<asp:TemplateField HeaderText="M%">
  <ItemTemplate>
    <span class='<%# int.Parse(Eval("M_PERC").ToString()) > 50 ? "MoreThanFifty" : "FiftyOrLess"  %>'>
      <%# Eval("M_PERC") %> %
    </span>
  </ItemTemplate>
</asp:TemplateField>

要将数字格式化为百分比,请查看BoundField.DataFormatString。例如:

<asp:BoundField DataField="PERC_OF_TARGET" 
                HeaderText="%" 
                DataFormatString="{0:F0}%" />

上面的格式字符串将用零位小数来格式化数字,如果您需要小数位数,则使用{0:F2}%,它将添加两位小数位数。

1)检查"templatefield"http://www.asp.net/data-access/tutorials/using-templatefields-in-the-gridview-control-cs

2) 见上文!编辑:下面是一个如何使用templatefield实现这一点的详细示例:如何在GridView 中实现条件格式

享受吧。