I agree with the other answers - the best solution (for both performance and code clarity) is to reverse engineer the page so that you can filter out invalid entries before data binding.
Most data sources do not allow us to delete their elements, while ASP.NET iterates. For example, if you bind to a simple generic List<T> , and you delete an item during iteration, the list will InvalidOperationException .
In other cases, ASP.NET actually iterates over a copy of the data source. If you bind to a DataTable , ASP.NET uses a copy of the content (by default the DataView), rather than iterating the source rows themselves - you can delete items from the underlying data source during the iteration, but this does not affect the data binding operations.
If filtering items in advance is not an option, your current solution is fine: just hide the items! If you need to correctly count the counter, track the number of invalid elements in the ItemDataBound handler and show it as a page-level property:
if (IsInvalid(args.Item.DataItem)) { this.invalidItemCount++;
Jeff sternal
source share