GridView RowDataBound doesn't fire on postback

2019-04-29 05:13发布

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?

8条回答
ら.Afraid
2楼-- · 2019-04-29 05:32
protected void btnHazardRating_Click(object sender, EventArgs e)
{
    gvPanelRole.RowDataBound += new GridViewRowEventHandler(gvPanelRole_RowDataBound);

    gvPanelRole.DataSource = dtGo;
    gvPanelRole.DataBind();
    ModalPopup.Show();

}
查看更多
ゆ 、 Hurt°
3楼-- · 2019-04-29 05:32

A page cannot process postback events unless it is rebuilt exactly as it was before (the postback). If you re-hide your links during the page-init, then your click events and such should fire. Unfortunately, without seeing some sample code I can't get more specific.

Also the data RowDataBound does not fire because you are not data binding. You are rebuilding the page from the viewstate- "viewstate binding" for lack of a better word.

查看更多
姐就是有狂的资本
4楼-- · 2019-04-29 05:33

Another solution is to put the logic in the LINQ query, so that you end up with a boolean LINQ field like "ShowParentLink". Then you can just bind the Visible property of the HyperLink field to that value - no RowDataBound required.

查看更多
家丑人穷心不美
5楼-- · 2019-04-29 05:35

I would have expected the viewstate to also reflect the fact that you have removed some of the links (assuming that they were removed before viewstate was saved).

Maybe thats the question you need to ask 'why do the removed links still appear in viewstate?'.

查看更多
萌系小妹纸
6楼-- · 2019-04-29 05:40

1) You could have a Method - ProcessDataRows() that would get called once on grid_DataBound(...). And then when you need it after PostBack.

And that way you process all rows when you want.

2) You could have methods like ShowParentLink(). That are then bound to the LinkButton in the grid (if you're using an ItemTemplate) and the link would have

Visible='<%#ShowParentLink()%>'
查看更多
beautiful°
7楼-- · 2019-04-29 05:44

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.

查看更多
登录 后发表回答