2009-06-29 5 views
6

모두 안녕하세요. 모두마스터 페이지를 사용할 때 C#의 콘텐츠 컨트롤에 액세스

저는 ASP.NET에서 페이지를 만들고이 과정에서 마스터 페이지를 사용하고 있습니다.

마스터 페이지에 Content Place Holder 이름 "cphBody"가 있습니다. 여기에는 해당 마스터 페이지가 마스터 페이지 인 각 페이지의 본문이 포함됩니다.

ASP.NET 웹 페이지에는 일부 컨트롤 (단추, Infragistics 컨트롤 등)이 들어있는 Content 태그 ("cphBody"참조)가 있으며 CodeBehind 파일에서 이러한 컨트롤에 액세스하려고합니다. 그러나 Content 태그에 중첩되어 있기 때문에 직접 (this.myControl ...) 할 수는 없습니다.

FindControl 메서드로 해결 방법을 찾았습니다.

ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder) Master.FindControl("cphBody"); 
ControlType myControl = (ControlType) contentPlaceHolder.FindControl("ControlName"); 

잘 작동합니다. 그러나, 나는 그것이 아주 좋은 디자인이 아니라고 의심하고 있습니다. 더 우아한 방법을 알고 계신가요?

감사합니다.

Guillaume Gervais.

+1

당신은 뒤에 콘텐츠 페이지의 코드 숨김에서 컨트롤에 액세스하려고, 또는 마스터 페이지의 코드 있는가에 텍스트 상자의 수의 변경? – wulimaster

+0

콘텐츠 페이지의 CodeBehind입니다. –

+0

그건 이상합니다. 동적으로 생성되고 추가되지 않는 한 콘텐트 페이지의 코드 숨김에서 컨트롤에 직접 액세스 할 수 있어야합니다. –

답변

4

릭 Strahl 좋은 설명이 여기에 (그리고 샘플 코드)가 - 나는 시도하고 대안이없는 경우를 제외하고의 FindControl을 피하기 http://www.west-wind.com/Weblog/posts/5127.aspx

+0

감사합니다. 그것은 기본적으로 내가 한 일이기 때문에 나를 위해 나의 방법을 검증합니다! –

+0

필자는 실제로 FindControl을 좋아하지 않습니다. 강력한 형식화 된 속성을 노출 할 수없고 미리 렌더링 된 출력을 파헤쳐 야 할 때만 필요합니다. – CRice

1

나는 재귀 적으로 파일을 ACESS이 코드를 사용

/// <summary> 
    /// Recursively iterate through the controls collection to find the child controls of the given control 
    /// including controls inside child controls. Return all the IDs of controls of the given type 
    /// </summary> 
    /// <param name="control"></param> 
    /// <param name="controlType"></param> 
    /// <returns></returns> 
    public static List<string> GetChildControlsId(Control control, Type controlType) 
    { 
     List<string> FoundControlsIds = new List<string>(); 
     GetChildControlsIdRecursive(FoundControlsIds, control, controlType); 

     // return the result as a generic list of Controls 
     return FoundControlsIds; 
    } 

    public static List<string> GetChildControlsIdRecursive(List<string> foundControlsIds, Control control, Type controlType) 
    { 
     foreach (Control c in control.Controls) 
     { 
      if (controlType == null || controlType.IsAssignableFrom(c.GetType())) 
      { 
       // check if the control is already in the collection 
       String FoundControl = foundControlsIds.Find(delegate(string ctrlId) { return ctrlId == c.ID; }); 

       if (String.IsNullOrEmpty(FoundControl)) 
       { 
        // add this control and all its nested controls 
        foundControlsIds.Add(c.ID); 
       } 
      } 

      if (c.HasControls()) 
      { 
       GetChildControlsIdRecursive(foundControlsIds, c, controlType); 
      } 
     } 
7

을, 일반적으로 깔끔한 방법이 있습니다.

어떻게 바로 뒤에 마스터 페이지 코드에서 코드를 호출 할 수 있도록 자녀 페이지

<%@ MasterType VirtualPath="~/MasterPages/PublicUI.Master" %> 

의 상단에 마스터 페이지의 경로를 포함하여 약. 당신이 컨트롤을 얻을 속성이 컨트롤을 반환 할, 또는 마스터 페이지에 방법을 만들 수 뒤에 마스터 페이지 코드에서 다음

public Label SomethingLabel 
{ 
    get { return lblSomething; } 
} 
//or 
public string SomethingText 
{ 
    get { return lblSomething.Text; } 
    set { lblSomething.Text = value; } 
} 

는 마스터 페이지에 라벨을 의미

<asp:Label ID="lblSomething" runat="server" /> 

사용법 :

Master.SomethingLabel.Text = "some text"; 
//or 
Master.SomethingText = "some text"; 
+0

그 반대의 경우는 어떨까요? 내 콘텐츠 페이지에'GridView'가 있는데 내 MasterPage에서 업데이트 할 수 있기를 원합니다. – Si8

+0

마스터 페이지에서 필요한 이벤트 데이터로 이벤트를 발생시키고 페이지와 함께 구독합니다. Master.SomeEvent + = SomeHandler; – CRice

3

아무것도 다른 할 일. 이 코드를 하위 페이지에 작성하면 마스터 페이지 레이블 컨트롤에 액세스 할 수 있습니다.

Label lblMessage = new Label(); 
lblMessage = (Label)Master.FindControl("lblTest"); 
lblMessage.Text = DropDownList1.SelectedItem.Text; 
1

안녕하세요 단지, 난 내 솔루션을 공유하고자 이것이 < ASP 내부에있는 '관리'에 액세스하기위한 작동 발견 : 제어판>는 'ContentPage'에 있지만의 C# 코드 숨김에서 'MasterPage'. 그것이 도움이되기를 바랍니다. 당신의 ContentPage에 ID = "PanelWithLabel"하고 RUNAT = "server"로 제어판> :

  1. 는 < ASP를 추가합니다.

  2. 패널 내에asp : Label> 컨트롤에 ID = "MyLabel"을 추가하십시오.

  3. 다음과 같이 MasterPage Code-behind에 함수를 쓰거나 (아래 복사/붙여 넣기) :이 컨트롤은 ContentPage의 레이블 컨트롤에 액세스합니다.이 컨트롤은 마스터 페이지 코드 숨김 그 텍스트는 마스터 페이지 :

    protected void onButton1_click(object sender, EventArgs e) 
    { 
    // find a Panel on Content Page and access its controls (Labels, TextBoxes, etc.) from my master page code behind // 
    System.Web.UI.WebControls.Panel pnl1; 
    pnl1 = (System.Web.UI.WebControls.Panel)MainContent.FindControl("PanelWithLabel"); 
    if (pnl1 != null) 
    { 
        System.Web.UI.WebControls.Label lbl = (System.Web.UI.WebControls.Label)pnl1.FindControl("MyLabel"); 
        lbl.Text = MyMasterPageTextBox.Text; 
    } 
    }