从里面的ControlCollection获取用户控件 [英] Get UserControl from inside ControlCollection

查看:876
本文介绍了从里面的ControlCollection获取用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我目前加入用户​​控件集合到一个面板集合。

So i am currently adding a collection of usercontrols to a Panel Collection.

下面是code

foreach (IssuePoll poll in issuePollList)
{
     IssuePollsUC issuePoll = (IssuePollsUC)Page.LoadControl("~/UserControls/IssuePollsUC.ascx");
     issuePoll.LoadPoll(poll, false, politician.PoliticianID);
     pnlUnFinishedTest.Controls.Add(issuePoll);
}

我试图让这些用户控件,所以我可以调用validate方法和保存内的每个这些控件的方法。这里是code我使用这一点,但它不工作。

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

无法转换类型'System.Web.UI.LiteralControl对象键入'UserControls.IssuePollsUC'

编辑:看起来,问题在于这样一个事实:控制不能转换成(用户控制)

Looks like the problem lies in the fact that a Control cannot be convert into (User Control)

推荐答案

有你的面板比你的用户控件即字面其他其他控件导致投失败。尝试

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.

修改

请注意,您必须在 Page_Init 事件不是的Page_Load 或其他地方添加动态控件。我怀疑你的控制甚至不存在 - 将它们添加不在 Page_Init 表示,他们是不是在的ViewState 和不会在任何控件集合present。

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.

这篇关于从里面的ControlCollection获取用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆