Dynamic TableStyles Based on Object Type

Here is an example of using different TableStyles depending on the type of the currently selected object in a DataGrid. I have 2 grids, each hooked to ExpressionHandles. I want to display a different set of columns, depending on the type of object in the top grid.
Firstly the application need to know when a new object has been selected. Here a CurrencyManager is being hooked up. dgStock is a DataGrid, ehRoot is an ExpressionHandle containing the Stock objects. 

private   cmStock: CurrencyManager;
....
procedure TfrmStock.TfrmStock_Load(sender: System.Object; e: System.EventArgs);
begin
  cmStock := CurrencyManager(dgStock.BindingContext[Self.ehRoot]);
  Include(cmStock.PositionChanged, Self.StockGridRowChanged);
end;

Then the event code that gets fired when the CurrencyManager position is changed. I revert back to using the CurrencyManagerHandle that is used to link the 2 grids to retrieve the current object. I've only used the CurrencyManager to alert me that the top grid has changed.

procedure TfrmStock.StockGridRowChanged(sender: System.Object; e: System.EventArgs);
begin...      if Stock(cmhStock.Element.AsObject).StockCategory.IsBoot then
      begin
        dgStockItems.TableStyles.Clear;

        dgStockItems.TableStyles.Add(self.tsItemsWithSole);
      end
      else
      begin
        dgStockItems.TableStyles.Clear;
        dgStockItems.TableStyles.Add(self.tsItemsNoSole);
      end;
...end;

To make this code more efficient, it makes sense to only change the TableStyle if is not the current TableStyle. To do this, we can ask the TableStylesCollection if it contains the required TableStyle. This works if we only ever have one TableStyle active at a time.

begin
  pnlItems.Visible := true;
  pnlPricing.Visible := true;
  if Stock(cmhStock.Element.AsObject).StockCategory.IsBoot and not
     dgStockItems.TableStyles.Contains(self.tsItemsWithSole) then
  begin
    dgStockItems.TableStyles.Clear;
    dgStockItems.TableStyles.Add(self.tsItemsWithSole);
  end
  else
  if not Stock(cmhStock.Element.AsObject).StockCategory.IsBoot and not
     dgStockItems.TableStyles.Contains(self.tsItemsNoSole) then
  begin
    dgStockItems.TableStyles.Clear;
    dgStockItems.TableStyles.Add(self.tsItemsNoSole);
  end;
end;

I hope this short article comes in handy to others.

 

Share this article!

Follow us!

Find more helpful articles: