简体   繁体   English

如何在 GridView 中实现条件格式化

[英]How to implement conditional formatting in a GridView

I have a GridView on my aspx page which displays a collection of objects defined by the following class我的 aspx 页面上有一个 GridView,它显示由以下 class 定义的对象集合

public class Item
{
    public string ItemName{get; set;}
    public object ItemValue{get; set;}
}

Then in my aspx markup I have something like this然后在我的 aspx 标记中我有这样的东西

<asp:GridView ID="MyTable" runat="server">
    <Columns>
        <asp:BoundField DataField="ItemName" />
        <asp:BoundField DataField="ItemValue" />
    </Columns>
</asp:GridView>

What I want to know is:我想知道的是:
Is there a way to use conditional formatting on the ItemValue field, so that if the object is holding a string it will return the string unchanged, or if it holds a DateTime it will displays as DateTime.ToShortDateString().有没有办法在 ItemValue 字段上使用条件格式,这样如果 object 保存一个字符串,它将返回未更改的字符串,或者如果它保存一个 DateTime,它将显示为 DateTime.ToShortDateString()。

Not sure if you can use a BoundField, but if you change it to a TemplateField you could use a formatting function like in this link .不确定是否可以使用 BoundField,但如果将其更改为 TemplateField,则可以使用格式 function ,如此链接

ie something like即类似的东西

<%# FormatDataValue(DataBinder.Eval(Container.DataItem,"ItemValue")) %>

Then in your codebehind, you can add a Protected Function然后在您的代码隐藏中,您可以添加受保护的 Function

Protected Function FormatDataValue(val as object) As String
    'custom enter code hereformatting goes here
End Function

Or you could do something in the OnRowCreated event of the gridview, like in this link或者您可以在 gridview 的 OnRowCreated 事件中执行某些操作,例如在此链接

<asp:GridView ID="ctlGridView" runat="server" OnRowCreated="OnRowCreated" />

this function is conditional formatting based on whether or not the datavalue is null/is a double这个 function 是基于数据值是否为空/是否为双精度的条件格式

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView drv = e.Row.DataItem as DataRowView;
        Object ob = drv["ItemValue"];


        if (!Convert.IsDBNull(ob) )
        {
            double dVal = 0f;
             if (Double.TryParse(ob.ToString(), out dVal))
             {
                 if (dVal > 3f)
                 {
                     TableCell cell = e.Row.Cells[1];
                     cell.CssClass = "heavyrow";
                     cell.BackColor = System.Drawing.Color.Orange;
                 }
             }
        }
    }
}

i decided with the Paul Rowland solution and more one thing "if (e.Item.DataItem is DataRowView)":我决定使用Paul Rowland解决方案和更多“如果(e.Item.DataItem 是 DataRowView)”:

    if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType ==                 ListItemType.AlternatingItem))
     {
       if (e.Item.DataItem is DataRowView)
       {
         DataRowView rowView = (DataRowView)e.Item.DataItem;
         String state = rowView[PutYourColumnHere].ToString();
         if (state.Equals("PutYourConditionHere"))
         {
           //your formating, in my case....
           e.Item.CssClass = "someClass";
         }
       }
     }

With BoundField you should modify your Item class.使用 BoundField 您应该修改您的项目 class。

If you don't want to modify your CodeBehind ther is a sort of trick you can do using a TemplateField:如果你不想修改你的 CodeBehind 有一种技巧,你可以使用 TemplateField:

        <asp:GridView ID="MyTable" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="ItemName" HeaderText="Name" />
            <asp:TemplateField HeaderText="Value">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# ((Eval("ItemValue") is DateTime) ? ((DateTime)Eval("ItemValue")).ToShortDateString() : Eval("ItemValue")) %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

obviously you can do it for any type of object but maybe your "Text" field would become.. complicated..显然你可以为任何类型的 object 做到这一点,但也许你的“文本”字段会变得......复杂......

by the way.. my CodeBehind for this example was just you class Item and this Page_Load():顺便说一句..我在这个例子中的 CodeBehind 就是你 class 项目和这个 Page_Load():

    protected void Page_Load(object sender, EventArgs e)
    {
        Item i1 = new Item();
        i1.ItemName = "name1";
        i1.ItemValue = "foo";
        Item i2 = new Item();
        i2.ItemName = "name2";
        i2.ItemValue = DateTime.Now;
        List<Item> list1 = new List<Item>();
        list1.Add(i1);
        list1.Add(i2);
        MyTable.DataSource = list1;
        MyTable.DataBind();
    }

and the result was correct;)结果是正确的;)

In .NET 2.0 is even easier:在 .NET 2.0 中更加容易:

Add this method to code behind: (this example formats a double value as million with 1 digit)将此方法添加到代码后面:(此示例将双精度值格式化为 1 位数的百万)

public string EvalAmount(string expression)
{
    double? dbl = this.Eval(expression) as double?;
    return dbl.HasValue ? string.Format("{0:0.0}", (dbl.Value / 1000000D)) : string.Empty;
}

In the aspx code, use this:在 aspx 代码中,使用这个:

<asp:TemplateField ItemStyle-Width="100px">
    <ItemTemplate>
        <asp:Label runat="server" Text='<%# EvalAmount("MyAmount") %>'></asp:
    </ItemTemplate>
</asp:TemplateField>

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

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