C# 如何在 GridView 中实现条件格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/661670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:20:24  来源:igfitidea点击:

How to implement conditional formatting in a GridView

c#.netgridviewasp.net-2.0

提问by Matthew Dresser

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

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

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 字段上使用条件格式,这样如果对象持有一个字符串,它将返回不变的字符串,或者如果它持有一个 DateTime,它将显示为 DateTime.ToShortDateString( )。

采纳答案by Paul Rowland

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,则可以使用此链接中的格式设置功能。

ie something like

即类似的东西

<%# 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

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

此函数是基于数据值是否为空/是否为双精度的条件格式

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

回答by p4bl0

With BoundField you should modify your Item class.

使用 BoundField 您应该修改您的 Item 类。

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..

显然,您可以为任何类型的对象执行此操作,但也许您的“文本”字段会变得……复杂……

by the way.. my CodeBehind for this example was just you class Item and this Page_Load():

顺便说一句..我在这个例子中的 CodeBehind 只是你对 Item 和这个 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 ;)

结果是正确的;)

回答by Stef Heyenrath

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>

回答by lucAlucard

i decided with the Paul Rowlandsolution 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";
         }
       }
     }