title: Extending a (ASP.NET) BoundField
body: <p>I would like to create a control that extends the BoundField that's used within a GridView.  What I'd like to do is provide another property named HighlightField that will be similar to the DataField property in that I want to give it the name a data column.  Given that data column it would see if the value is true or false and highlight the given text within the given column on the given row.</p>
  
  <p>Some psuedo-code if that doesn't make sense:</p>
  
  <pre><code>&lt;asp:GridView id="grid"&gt;
    &lt;Columns&gt;
      &lt;asp:BoundField DataField="Name" /&gt;
      &lt;cc:HighlightField DataField="Name" HighlightField="IsHighlighted" /&gt;
    &lt;/Columns&gt;
  &lt;/asp:GridView&gt;
  </code></pre>
  
  <p>And then within the databind or something:</p>
  
  <pre><code>if(this row's IsHighlighted value is true)
    set the CssClass of this datacell  = "highlighted"
  (or wrap a span tag around the text)
  </code></pre>
  
  <p>Ravish pointed me in the correct direction, here's what I ended up with:</p>
  
  <pre><code>public class HighlightedBoundField : BoundField
  {
      public string HighlightField
      {
          get { return ViewState["HighlightField"].ToString(); }
          set
          {
              ViewState["HighlightField"] = value;
              OnFieldChanged();
          }
      }
  
      public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
      {
          base.InitializeCell(cell, cellType, rowState, rowIndex);
  
          bool isDataRowAndIsHighlightFieldSpecified = cellType == DataControlCellType.DataCell &amp;&amp; !string.IsNullOrEmpty(HighlightField);
          if (isDataRowAndIsHighlightFieldSpecified)
          {
              cell.DataBinding += new EventHandler(cell_DataBinding);
          }
      }
  
      void cell_DataBinding(object sender, EventArgs e)
      {
          TableCell cell = (TableCell)sender;
          object dataItem = DataBinder.GetDataItem(cell.NamingContainer);
          cell.Text = DataBinder.GetPropertyValue(dataItem, DataField).ToString();
  
          bool highlightThisCellsText = Convert.ToBoolean(DataBinder.GetPropertyValue(dataItem, HighlightField));
          if (highlightThisCellsText)
          {
              cell.CssClass += " highlight";
          }
      }
  }
  </code></pre>