2014-02-24 3 views
1

FindControl에서 찾을 수 있도록 CheckBoxList에 동적으로 runat=server을 추가하고 싶습니다. 컨트롤 찾기 시도

CheckBoxList cbl = new CheckBoxList(); 
cbl.ID = "cbl" + intQuestionCount.ToString(); 

// get choices from choice list 
int intChoiceListId = Convert.ToInt32(detail.ChoiceListID); 
var choiceList = (from cl in _svsCentralDataContext.SVSSurvey_ChoiceListItems 
        where cl.ChoiceListID == intChoiceListId 
        orderby cl.Description 
        select cl); 
cbl.DataSource = choiceList; 
cbl.DataTextField = "Description"; 
cbl.DataBind(); 
cbl.Visible = true; 
cbl.CssClass = "PositionCol3"; 

questionsPanel.Controls.Add(cbl); 

나는이 개 재귀 찾기 제어 방법이 있습니다 (! IsPostBack을 경우),은 SQL 기록에 근거

private HtmlControl FindHtmlControlByIdInControl(Control control, string id) 
    { 
     foreach (Control childControl in control.Controls) 
     { 
      if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase) 
       && childControl is HtmlControl 
       ) 
      { 
       return (HtmlControl)childControl; 
      } 

      if (childControl.HasControls()) 
      { 
       HtmlControl result = FindHtmlControlByIdInControl(childControl, id); 
       if (result != null) 
       { 
        return result; 
       } 
      } 
     } 

     return null; 
    } 

    private WebControl FindWebControlByIdInControl(Control control, string id) 
    { 
     foreach (Control childControl in control.Controls) 
     { 
      if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase) 
       && childControl is WebControl 
       ) 
      { 
       return (WebControl)childControl; 
      } 

      if (childControl.HasControls()) 
      { 
       WebControl result = FindWebControlByIdInControl(childControl, id); 
       if (result != null) 
       { 
        return result; 
       } 
      } 
     } 

     return null; 
    } 

화면이 처음에 동적으로 생성됩니다. FindControl 메서드는 사용자가 '저장'버튼을 클릭하면이 로트가 표시된 후에 사용됩니다. 찾기 컨트롤 메서드가 내 CheckBoxList를 찾지 못했습니다 !!

+1

가지고있는 것은 이미 서버 측 컨트롤입니다. FindControl로 찾을 수 있어야합니다. – Andrei

+0

FindControl은 재귀 적이 지 않습니다. 문제가 있습니다. _이 메서드는 컨트롤이 지정된 컨테이너에 직접 포함되어있는 경우에만 컨트롤을 찾습니다. 즉,이 메서드는 컨트롤 내에서 컨트롤 내에서 검색하지 않습니다. http://msdn.microsoft.com/en-us/library/486wc64h%28v=vs.110%29.aspx – BlackICE

+0

이 컨트롤을 만들고 컨트롤 그룹에 추가 하시겠습니까? 추측 해 보면 페이지 수명주기에 너무 늦게 지나가고 있습니다. – ThatBlairGuy

답변

4

코드를 통해 컨트롤을 추가하고 있지만 이미 서버 쪽 컨트롤이므로 runat="server"을 추가 할 필요가 없습니다. 당신이 그들을 제대로 찾지 못했습니다.

페이지가 보이기 전에 추가되었는지 확인하십시오.

+0

컨트롤이 표시 되었기 때문에 컨트롤이 페이지에 추가되었습니다. 저장을 클릭하면 거기에 나타나지 않습니다. –

+0

@SteveStaple, 버튼을 클릭하면 '포스트 백'이 발생하고 웹에는 상태가 없으므로 해당 컨트롤이 손실됩니다. 당신은 그들의 상태를 유지해야합니다. 자세한 내용은 [이 질문] (http://stackoverflow.com/questions/17589268/dynamically-created-controls-losing-data-after-postback)과 [이 답변] (http : // stackoverflow. co.kr/a/4218690/961113) – Habib

+0

나는 마침내 작동하도록했습니다. 모든 동적 컨트롤의 세부 정보를 세션 변수에 저장해야하므로 OnInit을 다시 만들 수있었습니다. 시스템은 필드를 기억하지 못하는 경우에도 사용자가 필드에 입력 한 값을 기적적으로 기억합니다. –