代码之家  ›  专栏  ›  技术社区  ›  Frinavale

如何根据绑定到的对象的属性设置GridView行的行样式

  •  5
  • Frinavale  · 技术社区  · 15 年前

    我当前使用的是GridView,我希望根据行绑定到的对象的属性为该行设置CSSClass。

    我尝试了以下方法,但不起作用(见评论):

    <asp:GridView id="searchResultsGrid" runat="server" AllowPaging="true" PageSize="20" AutoGenerateColumns="false">
    
    <!-- The following line doesn't work because apparently "Code blocks 
    aren't allowed in this context: -->
      <RowStyle CssClass="<%#IIF(DataBinder.Eval(Container.DataItem,"NeedsAttention","red","") %>
    
      <Columns>
    <!--............-->
      </Columns>
    </asp:GridView>
    

    现在,我可以简单地处理GridView的rowdatabound事件,并在那里更改行的CSS类……但我正在尝试在UI和页面/业务逻辑层之间保持清晰的分离。

    3 回复  |  直到 10 年前
        1
  •  4
  •   Jeff Sternal    15 年前

    在声明性标记中不能这样做。

    几乎所有 GridView 的声明性属性(包括 GridView.RowStyle )是网格级别设置而不是行级别。除了 TemplateFields ,它们不是绑定的数据容器,因此无法访问其行中的数据。

    如果要在.aspx模板中保留此逻辑,唯一的实际选项是使用模板字段并操作其内容:

    <asp:TemplateField>
        <ItemTemplate>
            <span class="<%# ((string)Eval("property3")) == "NeedsAttention" ? "red" : string.Empty %>">
                <%# Eval("property1") %>
            </span>
        </ItemTemplate>                        
    </asp:TemplateField>
    

    取决于你想做什么,这可能会很尴尬-你没有权限访问 <td> (或) <tr> 为此,您必须为每个单元格重复格式化。

    这个 GRIDVIEW 类会花费大量的时间来隐藏HTML的细节和样式。毕竟你 能够 创建一个 GRIDVIEW control adapter 它甚至不会呈现为HTML表。(尽管可能不太可能。)

    所以即使你试图避免它,你最好还是在 OnRowDataBound 处理程序-或使用 Repeater (如果合适的话)。

        2
  •  2
  •   Joel    14 年前

    我知道已经快一年了,但是如果有人尝试这样做,请尝试对GridView进行子类划分。

    public class GridViewCSSRowBindable : GridView
    {
      public string DataFieldRowCSSClass { get; set; }
      protected override void OnRowDataBound(GridViewRowEventArgs e)
      {
        base.OnRowDataBound(e);
        if (!string.IsNullOrEmpty(DataFieldRowCSSClass))
        {
          //This will throw an exception if the property does not exist on the data item:
          string cssClassString = DataBinder.Eval(e.Row.DataItem, DataFieldRowCSSClass) as string;
          if (!string.IsNullOrEmpty(cssClassString))
          {
            string sep = string.IsNullOrEmpty(e.Row.CssClass) ? string.Empty : " ";
            e.Row.CssClass += sep + cssClassString;
          }
        }
      }
    }
    

    然后在您的页面中:

    <custom:GridViewCSSRowBindable ID="gvExample" runat="server" DataFieldRowCSSClass="RowCSS">
    </custom:GridViewCSSRowBindable>
    

    绑定到此示例GridView的对象应具有公共字符串rowcss属性。

    如果以前没有使用继承的控件,则可能需要在项目中查找如何设置该控件。

        3
  •  0
  •   Rahil Wazir Joseph Daigle    10 年前
    foreach (TableCell gvc in gvRowPhistry.Cells)
    {
        gvc.ForeColor = System.Drawing.Color.Blue;
    }