Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

c# - find a control in current page

Hello, my problem is that I can't seem to find the control from current page. My page class has the following code:

        <div class="meeting_body_actions"> 
                <efv:ViewMeetingActions ID="ViewMeetingActions" runat="server" />
        </div>

My control has:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ViewMeetingActions.ascx.cs" Inherits="EFV.Controls.ViewMeetingActions" %>
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>

Telerik:RadListBox runat="server"  CssClass="RadListBox" ID="listbox_action_member" Width="125" Height="200px" Skin="Telerik" OnTransferring="ActionListBoxViewer_Transferring" OnDeleting="ActionListBoxViewer_Deleting" >
         <ButtonSettings AreaHeight="30" Position="Bottom" HorizontalAlign="Center" />  
        <HeaderTemplate>               
        </HeaderTemplate>
        <Items>
        </Items>
      <FooterTemplate>
          <asp:DropDownList runat="server" ID="action_member_dropdown"  Height="22" Width="125"  ></asp:DropDownList>
        </FooterTemplate>
    </telerik:RadListBox

From an other control I need to throw information in the "action_member_dropdown";

  Control control = this.Page.FindControl("ViewMeetingActions");
  -> doesnt work

        Page page = HttpContext.Current.Handler as Page;
        Control ViewMeetingActions = page.FindControl("ViewMeetingActions");
        -> didnt work as well

Page test = this.Parent.Page;
-> no succes

If I ask the page how many controls I have it says I have 1 control, and I added more then 5.

So in short, how do I call a control from the same page from an other control?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If a control is nested inside other controls, you need to find it recursively.

Here is a helper method. It searches a control recursively.

Helper Method

public static Control FindControlRecursive(Control root, string id)
{
   if (root.ID == id) 
     return root;

   return root.Controls.Cast<Control>()
      .Select(c => FindControlRecursive(c, id))
      .FirstOrDefault(c => c != null);
}

Usage

var myControl =  (MyControl)FindControlRecursive(Page, "ViewMeetingActions"); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...