C# – Dynamically Add Footer to ASP.NET GridView

asp.netcfootergridview

I am trying to add a footer row of DropDownLists to my GridView control. The problem is that I do not know how many columns will be in my DataSource at design time, so I am trying to use the AutoGenerateColumns=true and not specify the column templates. Therefore the way I am adding the DropDownList controls to the footer is in code dynamically on the DataBound event of the GridView.

This works fine except that I would like to do something with the SelectedItem of each of the DropDownLists when the users clicks a button. These dynamically added controls no longer seem to exist on the post back of the user clicking the button, I believe the problem is because I am not specifying the runat="server" tag on the DropDownList controls.

Is there a different way I could be adding these drop downs to a FooterTemplate without specifying all of the columns so I can have access to their SelectedItems when the user clicks a button on the page?

Best Answer

You're partially right -- the dynamically added controls don't exist anymore after the postback. They won't get re-added until the DataBound event is run. The problem is that Databinding events happen after control events, that is, after your button's Click event. So, at the point in the page lifecycle where the click event is handled, those controls haven't been recreated yet.

Here's a related question which might have some useful information.

Related Topic