问题
So i am currently adding a collection of usercontrols to a Panel Collection.
Here is that code
foreach (IssuePoll poll in issuePollList)
{
IssuePollsUC issuePoll = (IssuePollsUC)Page.LoadControl("~/UserControls/IssuePollsUC.ascx");
issuePoll.LoadPoll(poll, false, politician.PoliticianID);
pnlUnFinishedTest.Controls.Add(issuePoll);
}
I am trying to get those usercontrols so i can call a validate method and save method inside each of those controls. Here is the code i am using for that, but it is not working.
foreach (Control control in pnlUnFinishedTest.Controls)
{
IssuePollsUC issuePolls = (IssuePollsUC)control;
issuePolls.SavePollAnswer(appUser.User.PersonID);
}
I get an error message on the convert, it says
"Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'UserControls.IssuePollsUC'"
EDIT: Looks like the problem lies in the fact that a Control cannot be convert into (User Control)
回答1:
There are other controls in your panel other than your user control i.e. the literal that is causing the cast to fail. Try
foreach (Control control in pnlUnFinishedTest.Controls)
{
IssuePollsUC issuePolls = control as IssuePollsUC;
if(issuePolls != null)
{
issuePolls.SavePollAnswer(appUser.User.PersonID);
}
}
This will make it more type safe.
EDIT
Please note that you must add dynamic controls in the Page_Init
event not Page_Load
or anywhere else. I suspect your controls aren't even there - adding them not in Page_Init
means that that they are not in ViewState
and won't be present in any control collection.
来源:https://stackoverflow.com/questions/8932843/get-usercontrol-from-inside-controlcollection