怎么算,我在一个页面的用户控制的数量? [英] How to count the number of user controls that I have in a page?

查看:113
本文介绍了怎么算,我在一个页面的用户控制的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了5用户控件的页面。我希望做更多的与他们,但现在,我只想用下面的方法来计数。

 无效btnFormSave_Click(对象发件人,EventArgs的发送)
{
  INT I = 0;
  收集的ControlCollection = Page.Controls;
  的foreach(在集散控制CTR)
  {
    如果(CTR是用户控件)
    {
      我++;
    }
   }
}

当我调试这个code,I = 1,控制母版页(我不知道该母版页的用户控件)。

我如何指望是我的网页上用户控件?

修改

这是我的内容占位符标记。

 < ASP:内容ID =cntMain=服务器ContentPlaceHolderID =ContentMain>


解决方案

编辑:用下面的更换本人原创,关闭基地的答案

您可能需要改乘控制控件中(也许成面板?)。

http://msdn.microsoft.com /en-us/library/yt340bh4(v=vs.100).aspx


  

这个例子只查找包含在Pa​​ge对象的控件和
  于页的直接子控件。它没有找到
  文本框是依次的子控件的孩子
  这一页。例如,如果添加了Panel控件到页面,小组
  控制是由包含在HtmlForm控件的子
  页面,它会在这个例子中找到。但是,如果你再
  添加一个TextBox控件到Panel控件,TextBox控件
  文本将不被实施例被显示,因为它不是一个子
  在网页的或者说是在网页的子控制的。更
  走在控制实际应用这种方法是
  创建一个递归方法,可以调用走路控件
  收集,因为它遇到的每个控制。


编辑2:SO上添加链接递归控制搜索示例

例如使用LINQ: http://stackoverflow.com/a/253962/704808

传统的例子: http://stackoverflow.com/a/4955836/704808

I have a page that has 5 user controls. I want to do more with them, but for now, I just want to count them using the following method.

void btnFormSave_Click(object sender, EventArgs e)
{
  int i = 0;
  ControlCollection collection = Page.Controls;
  foreach (Control ctr in collection)
  {
    if (ctr is UserControl)
    {
      i++;
    }
   }
}

When I debug this code, i = 1, and the control is the master page (I didn't know that the master page is a user control).

How do I count user controls that are on my page?

EDIT

This is my content placeholder markup.

<asp:Content ID="cntMain" runat="Server" ContentPlaceHolderID="ContentMain">

解决方案

EDIT: Replacing my original, off-base answer with the following.

You probably need to recurse to controls within controls (perhaps into a Panel?).

http://msdn.microsoft.com/en-us/library/yt340bh4(v=vs.100).aspx

This example finds only the controls contained in the Page object and the controls that are direct children of the page. It does not find text boxes that are children of a control that is in turn a child of the page. For example, if you added a Panel control to page, the Panel control would be a child of the HtmlForm control contained by the Page, and it would be found in this example. However, if you then added a TextBox control into the Panel control, the TextBox control text would not be displayed by the example, because it is not a child of the page or of a control that is a child of the page. A more practical application of walking the controls this way would be to create a recursive method that can be called to walk the Controls collection of each control as it is encountered.

EDIT 2: Adding links to recursive control search examples on SO.

Example using LINQ: http://stackoverflow.com/a/253962/704808

Traditional example: http://stackoverflow.com/a/4955836/704808

这篇关于怎么算,我在一个页面的用户控制的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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