GridView RowDataBound doesn't fire on postback


Question

On an ASP.NET page, I have a GridView populated with the results of a LINQ query. I'm setting the DataSource in code, then calling DataBind on it. In the GridView's RowDataBound event, I'm selectively hiding links in some GridView fields based on the query results. (For instance, I hide the "Show Parent" link of the row in question has no parent row.)

This works fine initially. But on postback (when I don't call DataBind, but the GridView stays populated through ViewState), the data displays, but the RowDataBound event (obviously) doesn't fire, and my links don't get hidden.

What's the best way to get the links to be hidden after a postback?

1
6
11/11/2008 3:21:27 PM

Accepted Answer

Here's how I ended up solving this:

  1. I created a serializable class with readonly properties: PK of a row, and a boolean for each link indicating whether it's enabled or not. We'll call it LinkVisibility.
  2. I created a serializable class inheriting from KeyedCollection to hold instances of the class above.
  3. I created a ViewState-backed property holding an instance of that collection.
  4. In my Search procedure (populating the GridView), I clear the collection.
  5. In RowDataBound, which initially shows/hides the links, I add a LinkVisibility instance to the collection for each row.
  6. In Page.Load, when IsPostBack is true, I loop through the GridView rows. I look up the LinkVisibility for each one by PK in the collection (DataKeyNames is set in the GridView), and I set the links accordingly.

I don't know that this is the best way to do this, but it certainly does work, which is more than I can say for anything else I've tried.

2
11/12/2008 9:33:15 PM

The RowDataBound event only fires when the GridView's data changes during the postback. The event is short-circuited for speed so it's not re-generating the exact same data unnecessarily. Use the RowCreated event to manipulate the HTML instead - it fires on every postback regardless of whether the data has changed.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon