【问题标题】:Get UserControl from inside ControlCollection从 ControlCollection 中获取 UserControl
【发布时间】:2012-01-19 20:31:39
【问题描述】:

所以我目前正在将一组用户控件添加到面板集合中。

这是代码

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

我正在尝试获取这些用户控件,以便我可以在每个控件中调用验证方法和保存方法。这是我为此使用的代码,但它不起作用。

foreach (Control control in pnlUnFinishedTest.Controls)
{
     IssuePollsUC issuePolls = (IssuePollsUC)control;
     issuePolls.SavePollAnswer(appUser.User.PersonID);
}

我在转换时收到一条错误消息,上面写着

“无法将“System.Web.UI.LiteralControl”类型的对象转换为“UserControls.IssuePollsUC”类型”

编辑:看起来问题在于无法将控件转换为(用户控件)

【问题讨论】:

  • 具体是什么不起作用?它没有找到控件?
  • 我在转换时收到一条错误消息,它显示“无法将 'System.Web.UI.LiteralControl' 类型的对象转换为 'UserControls.IssuePollsUC'”

标签: asp.net user-controls


【解决方案1】:

除了用户控件之外,您的面板中还有其他控件,即导致强制转换失败的文字。试试

foreach (Control control in pnlUnFinishedTest.Controls) 
{    
     IssuePollsUC issuePolls = control as IssuePollsUC;      

     if(issuePolls != null)
     {
          issuePolls.SavePollAnswer(appUser.User.PersonID); 
     } 
}

这将使它更安全。

编辑

请注意,您必须在 Page_Init 事件中添加动态控件,而不是在 Page_Load 或其他任何地方。我怀疑您的控件甚至都不存在 - 不在Page_Init 中添加它们意味着它们不在ViewState 中并且不会出现在任何控件集合中。

【讨论】:

  • 我已经尝试过使用您在上面尝试过的方法,它给了我相同的结果。在使用 Page_Init 时,控件实际上已加载并且在 page_load 中加载它的页面上可见。所以控件就在那里,并且面板的控件集合中有一个对象(无论如何它应该是那里唯一的对象)。
  • @AndyXufuris。我有点不清楚。那你还有例外吗?如果是在哪一行代码。 as 关键字应该防止抛出异常。这个 SO 问题stackoverflow.com/questions/227121/… 正在做你想做的事情,即 foreach(plhMediaBuys.Controls 中的 UserControl uc)。这有帮助吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 2023-03-31
  • 2010-10-25
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 2017-11-09
相关资源
最近更新 更多