How to get the information from a dynamically created TableRow C#/Asp.Net?
-
27-10-2019 - |
Question
Alright so in the project I am working on I am making a hard coded asp:panel on the page and then filling it with:
- A Drop Down list
- An asp:Table, with an asp:TableHeaderRow
- Add and Cancel Buttons
When the selectedIndexChanged event happens with the DropDownList the tablerow gets created then filled with 6 or so tablecells which then get asp:Textboxes placed inside of them.
Eventually they all get added to the tablerow which then gets added to the tablerowcollection.
That all works just fine,but when I go to add the information from these dynamically created TableRows
with a foreach loop they are no where to be found but the TableHeaderRow is.
Also when I click add and let it go through the process I get no null exceptions and the only thing left after it is the header, all my rows disappear.
Anyways I feel that I am just missing something really dumb. I've looked through a lot of forums, posts, MSDN and never found an answer to my problem. Any help would greatly be appreciated!
Solution
You need to add your dynamic rows to your Table in Page_Init
not Page_Load
. If you are creating it in Page_Load
your new rows won't be added to ViewState and you will see this problem.
Unfortunately you are adding them in response to a server side event which can get tricky. You still need to add the rows in Page_Init
but when the page posts back and you at in Page_Init
then the selectedIndexChanged
event hasn't yet fired. It's too early in the page lifecycle.
If you want to know if it has fired at Page_Init
the only way I have found is by examining Request.Form("__EVENTTARGET")
collection at that point. This contains the control ID of the control that has triggered the postback - in your case this will be the dropdown list. The control that fired the event will be there but the ID will be qualified i.e not MyControID but ctl_MasterPageContentHolderID_NamingContainer1_MyControlID` or the like - so you will have to take it into account when looking for it. Once you have identified that that event has fired then you can add the rows. Once they are added there then they won't disappear.
As I say it is tricky to get working but I have done this successfully in the past. Generally dynamic controls can be very hard to work with for just this reason. You may want to consider alternatives. Best of luck with it anyway though.