pyram
pyram

Reputation: 935

asp.net, Gridview RowEditing event only works on first row

Im working on asp.net with c#. I have a gridview with templatefield columns, data comes from an sql database. I have linkbutton on the item template, the linkbutton calls the Rowediting event to enable the editing. This works fine on the first row. But when I click on any of the other rows nothing happens, the event never gets fires.

How can I solve this?

Thanks..

Upvotes: 1

Views: 3491

Answers (1)

David
David

Reputation: 73574

Most likely you are data-binding the grid in the Page_Load event. If this is the case, the ASP.NET Page Lifecycle is getting in your way. (Be sure to read the article in the link provided. Every .NET developer needs to know about the Page_Lifecycle. It explains a lot of behavior thaqt would otherwise cause confusion, such as this behavior.)

The Page_Load event happens on every postback - every button click, or any event that triggers the postback.

If this is the case, there are two possible options:

  1. Move your data binding code to Page_Init
  2. Put your data-binding in Page_Load inside an if(!Page.IsPostback) block.

In essence, the problem is that your page is data-binding on the first load. Then the editing event is triggered by some client action, which triggers a postback. In this postback, Page_Load fires first, which re-binds the GridView, erasing all of the data that was associated with it on the previous load. So when the RowEditing event fires (control events always happen AFTER Page_Load) there's nothing for it to do. All references to the data as it existed before postback are gone.

If you move your binding code too Page_Init, you can get around this because the page will be bound, and then all of the Viewstate will be re-applied to it, restoring the data that was lost in the postback in the scenario above.

Upvotes: 3

Related Questions