如何在 GridView 中实现条件格式 [英] How to implement conditional formatting in a GridView

查看:24
本文介绍了如何在 GridView 中实现条件格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 aspx 页面上有一个 GridView,它显示由以下类定义的对象集合

I have a GridView on my aspx page which displays a collection of objects defined by the following class

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

然后在我的 aspx 标记中我有这样的东西

Then in my aspx markup I have something like this

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

我想知道的是:
有没有办法在 ItemValue 字段上使用条件格式,以便如果对象持有一个字符串,它将返回未更改的字符串,或者如果它持有一个 DateTime,它将显示为 DateTime.ToShortDateString().

推荐答案

不确定是否可以使用 BoundField,但如果将其更改为 TemplateField,则可以使用类似 此链接.

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.

即类似的东西

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

然后在你的代码隐藏中,你可以添加一个受保护的函数

Then in your codebehind, you can add a Protected Function

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

或者你可以在 gridview 的 OnRowCreated 事件中做一些事情,比如在 这个链接

Or you could do something in the OnRowCreated event of the gridview, like in this link

<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

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;
                 }
             }
        }
    }
}

这篇关于如何在 GridView 中实现条件格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆