Get UserControl from inside ControlCollection

大城市里の小女人 提交于 2020-01-15 11:08:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!