2009-07-24 6 views
1

프로그램 디버깅을 시작한 후 다음 오류가 발생합니다. 이 문제를 해결하는 방법을 알고 있습니까?NullReferenceException Controls.Add C# 오류

System.NullReferenceException was unhandled by user code 
Message="Object reference not set to an instance of an object." 

그것은 광고 참조 경우 : CreateDropDownLists있어서 내부

pnlDropDownList.Controls.Add(ddl); 

. 분명히 ddl은 null 개체 여야합니다. 비록이 동일한 메서드에서 ddl을 직전에 초기화했지만 말입니다. 이 오류가 발생하는 이유를 이해합니까? 아래 코드를 참조하십시오 ...

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.SqlClient; 
using System.Diagnostics; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using ADONET_namespace; 
using MatrixApp; 

namespace AddFileToSQL 
{ 
public partial class DataMatch : _Default 
{ 

protected System.Web.UI.WebControls.PlaceHolder phTextBoxes; 
protected System.Web.UI.WebControls.PlaceHolder phDropDownLists; 
protected System.Web.UI.WebControls.Button btnAnotherRequest; 
protected System.Web.UI.WebControls.Panel pnlCreateData; 
protected System.Web.UI.WebControls.Literal lTextData; 
protected System.Web.UI.WebControls.Panel pnlDisplayData; 
Panel pnlDropDownList; 
protected static string inputfile2; 
static string[] headers = null; 
static string[] data = null; 
static string[] data2 = null; 
static DataTable myInputFile = new DataTable("MyInputFile"); 
static string[] myUserSelections; 

// a Property that manages a counter stored in ViewState 
protected int NumberOfControls 
{ 
get { return (int)ViewState["NumControls"]; } 
set { ViewState["NumControls"] = value; } 
} 

public void EditRecord(object recordID) 
{ 
SelectedRecordID = recordID; 
// Load record from database and show in control 
} 

protected object SelectedRecordID 
{ 
get 
{ 
return ViewState["SelectedRecordID"]; 
} 

set 
{ 
ViewState["SelectedRecordID"] = value; 
} 
} 

protected void OnPreLoad(object sender, EventArgs e) 
{ 

//Create a Dynamic Panel 
pnlDropDownList = new Panel(); 
pnlDropDownList.ID = "pnlDropDownList"; 
pnlDropDownList.BorderWidth = 1; 
pnlDropDownList.Width = 300; 
this.form1.Controls.Add(pnlDropDownList); 
} 

// Page Load 
private void Page_Load(object sender, System.EventArgs e) 
{ 
if (!Page.IsPostBack) 
{ 
this.NumberOfControls = 0; 
} 
} 

// Add DropDownList Control to Placeholder 
private void CreateDropDownLists() 
{ 
for (int counter = 0; counter < NumberOfControls; counter++) 
{ 
DropDownList ddl = new DropDownList(); 
SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable); 
ddl.ID = "DropDownListID" + (counter + 1).ToString(); 
ddl.DataTextField = "COLUMN_NAME"; 
ddl.DataValueField = "COLUMN_NAME"; 
ddl.DataSource = dr; 
ddl.DataBind(); 
ddl.AutoPostBack = true; 
ddl.EnableViewState = true; //Preserves View State info on Postbacks 
ddl.Style["position"] = "absolute"; 
ddl.Style["top"] = 100 * counter + 80 + "px"; 
ddl.Style["left"] = 250 + "px"; 
ddl.SelectedIndexChanged += new EventHandler(this.OnSelectedIndexChanged); 
pnlDropDownList.Controls.Add(ddl); 
pnlDropDownList.Controls.Add(new LiteralControl("<br><br><br>")); 
dr.Close(); 
} 
} 

private void CreateLabels() 
{ 
for (int counter = 0; counter < NumberOfControls; counter++) 
{ 
Label lbl = new Label(); 
lbl.ID = "Label" + counter.ToString(); 
lbl.Text = headers[counter]; 
lbl.Style["position"] = "absolute"; 
lbl.Style["top"] = 100 * counter + 50 + "px"; 
lbl.Style["left"] = 250 + "px"; 
pnlDropDownList.Controls.Add(lbl); 
pnlDropDownList.Controls.Add(new LiteralControl("<br><br><br>")); 
} 
} 

// Add TextBoxes Control to Placeholder 
private void RecreateDropDownLists() 
{ 
for (int counter = 0; counter < NumberOfControls; counter++) 
{ 
DropDownList ddl = new DropDownList(); 
SqlDataReader dr = ADONET_methods.DisplayTableColumns(targettable); 
ddl.ID = "DropDownListID" + (counter + 1).ToString(); 
ddl.DataTextField = "COLUMN_NAME"; 
ddl.DataValueField = "COLUMN_NAME"; 
ddl.DataSource = dr; 
ddl.DataBind(); 
myUserSelections[counter] = ""; 
dr.Close(); 
ddl.AutoPostBack = true; 
ddl.EnableViewState = false; //Preserves View State info on Postbacks 
ddl.Style["position"] = "absolute"; 
ddl.Style["top"] = 100 * counter + 80 + "px"; 
ddl.Style["left"] = 250 + "px"; 
pnlDropDownList.Controls.Add(ddl); 
pnlDropDownList.Controls.Add(new LiteralControl("<br><br><br>")); 
} 
} 

// Create TextBoxes and DropDownList data here on postback. 
protected override void CreateChildControls() 
{ 
// create the child controls if the server control does not contains child controls 
this.EnsureChildControls(); 
// Creates a new ControlCollection. 
this.CreateControlCollection(); 
// Here we are recreating controls to persist the ViewState on every post back 

if (Page.IsPostBack) 
{ 
RecreateDropDownLists(); 
RecreateLabels(); 
} 

// Create these conrols when asp.net page is created 
else 
{ 
PopulateFileInputTable(); 
CreateDropDownLists(); 
CreateLabels(); 
} 

// Prevent child controls from being created again. 
this.ChildControlsCreated = true; 
} 

private void AppendRecords() 
{ 
switch (targettable) 
{ 
case "ContactType": 
for (int r = 0; r < myInputFile.Rows.Count; r++) 
{ ADONET_methods.AppendDataCT(myInputFile.Rows[r]); } 
break; 
case "Contact": 
for (int r = 0; r < myInputFile.Rows.Count; r++) 
{ ADONET_methods.AppendDataC(myInputFile.Rows[r]); } 
break; 
case "AddressType": 
for (int r = 0; r < myInputFile.Rows.Count; r++) 
{ ADONET_methods.AppendDataAT(myInputFile.Rows[r]); } 
break; 

default: throw new ArgumentOutOfRangeException("targettable type", targettable); 
} 
} 

// Read all the data from TextBoxes and DropDownLists 
protected void btnSubmit_Click(object sender, System.EventArgs e) 
{ 
int cnt = FindOccurence("DropDownListID"); 
EditRecord("DropDownListID" + Convert.ToString(cnt + 1)); 
AppendRecords(); 
pnlDisplayData.Visible = false; 
} 

private int FindOccurence(string substr) 
{ 
string reqstr = Request.Form.ToString(); 
return ((reqstr.Length - reqstr.Replace(substr, "").Length)/substr.Length); 
} 

#region Web Form Designer generated code 

override protected void OnInit(EventArgs e) 
{ 
InitializeComponent(); 
base.OnInit(e); 
} 

private void InitializeComponent() 
{ 
(this.btnSubmit_Click); 
} 

#endregion 

} 
} 

답변

3

"pnlDropDownList"는 Null 개체라고 생각합니다. 그 함수는 "pnlDropDownList = new Panel();"전에 호출되어야합니다. "OnPreLoad"에. 중단 점을 사용하여 소스를 단계별로 진행하고 코드 경로를 따르십시오. 이 경우를 알게 될 것입니다. 당신은 PreInit에서 동적 컨트롤을 만드는 시도 할 수도

+0

을 확인 패널이 아직 초기화되지 않았 음을 직감 따라서 예외를 가지고, 그것을 해결할 수 있습니다 생성자에서 이벤트 대신 pnlDropDownList를 초기화합니다. –

+0

@Martinho, 고맙습니다. 해결책을 제시하고 문제를 언급해야했습니다. –

+0

고마워, 고쳐! – salvationishere

관련 문제