2012-06-11 6 views
0

사용자 입력을위한 27 개의 DropDownLists가 포함 된 표가 있습니다. 내 표는이 HTML의 27 개 항목을 가지고 : 스팬이 S1, S2, ..., S27를 색인하고 자리가 P1, P2, ..., P27를 색인여러 개의 DropDownLists 만들기

<span id="s1" runat="server"><asp:PlaceHolder ID="p1" runat="server"></asp:PlaceHolder></span> 

. 스팬이 인덱싱되는 이유는 DropDownList를 어떤 선택 으로든 바꿀 수 있기 때문입니다. 즉, DropDownList가 사라집니다. 여기

내가 DropDownLists를 생성하고 방법입니다

protected void Page_Load(object sender, EventArgs e) 
{ 
    var data = CreateDataSource(); 
    int x; 
    for (x = 1; x <= 27; x++) 
    { 
     DropDownList dl = new DropDownList(); 
     string index = x.ToString(); 
     dl.ID = "TrendList" + index; 
     dl.AutoPostBack = true; 
     dl.SelectedIndexChanged += new EventHandler(this.Selection_Change); 
     dl.DataSource = data; 
     dl.DataTextField = "TrendTextField"; 
     dl.DataValueField = "TrendValueField"; 
     dl.DataBind(); 
     if (!IsPostBack) 
     { 
      dl.SelectedIndex = 0; 
     } 
     PlaceHolder ph = (PlaceHolder)form1.FindControl("p" + index); 
     ph.Controls.Add(dl); 
    } 
} 

런타임 오류가 마지막 줄에서 발생한다. 내가 원하는 DropDownList로를 선택하고 선택을하지만 두 번째 DropDownList로를 선택하고 선택을 할 때이 오류를 얻을 수 있습니다 :

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. 

Line 46:    } 
Line 47:    PlaceHolder ph = (PlaceHolder)form1.FindControl("p" + index); 
Line 48:    ph.Controls.Add(dl); 
Line 49:   } 

이 내가 무력으로 그 일을 할 때 작동하는 것 같았다 :

p1.Controls.Add(DropList1); 
p2.Controls.Add(DropList2); 
etc.... 

하지만 이제 오류가 발생합니다. 이 디버거에서 실행할 수 있지만 null 참조를 찾을 수 없습니다.

모든 조언을 주시면 감사하겠습니다.

감사합니다.

답변

0

이 함수는 모든 새 페이지마다 호출되었다는 것이 밝혀졌습니다. 첫 번째 실행 후 첫 번째 자리 표시자가 더 이상 존재하지 않아 null 참조 오류가 발생했음을 의미합니다. 이 코드로 문제가 해결되었습니다 :

if (placeHolder != null) 
{ 
    placeHolder.Controls.Add(ddl); 
} 
0

하나의 자리 표시 자만 사용해 보셨습니까? 오류 메시지는 "p"+ index.ToString() ID로 자리 표시자가없는 것 같습니다.

0

자리 표시자는 기술적으로 form1이 아니며 form1에있는 범위에 있습니다 또는 범위가 다른 제어 등).

이 스팬이 Form1에 중첩되어있는 상황에서 작동합니다 :

var s = form1.FindControl("s" + index); 
var ph = s.FindControl("p" + index); 
ph.Controls.Add(dl); 
+0

감사합니다. 나는 이것을 시도하고 같은 널 포인터 예외가있다. – Kevin

+0

@Kevin - 전체 마크 업 (모든 형식 1, 어쨌든)을 게시하려면 올바른 코드를 찾아 볼 수 있는지 살펴 보겠습니다. – hmqcnoesy

0

FindControl 방법은 재귀하지, 당신은 중첩 된 객체를 반복하는 방법을 사용해야합니다 그래서. 여기에 좋은 예제가 여기에 있습니다 : C#, FindControl

+0

링크를 제공해 주셔서 감사합니다. 재귀 적으로 검색을 시도했지만 여전히 동일한 null 포인터 예외가 발생합니다. – Kevin

관련 문제