我正在创建一个调查页面,该页面从数据库中提取以根据其类型显示问题,对于每种类型,我都创建了一个用户控件。在Page_Load
,我将用户控件放在这样的占位符中:-(QNO 是我在上一页设置为 0 的会话,只是为了开始问题顺序)
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection Connection = DatabaseConnection.GetSurveySystemConnection();
string sqlquery = "SELECT Q.[ID], Q.[Question_Order], Q.[Question], QT.[Type_Desc] FROM [Questions] Q Inner join Question_Type QT On Q.Type_ID= QT.ID Where Q.[Survey_ID] =" + Session["Survey_ID"] + "Order by Question_Order";
SqlCommand cmd = new SqlCommand(sqlquery, Connection);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable DT = new DataTable();
da.Fill(DT);
if (DT != null)
{
Session["Count"] = DT.Rows.Count;
QuestionLabel.Text = String.Format("{0}.{1}", DT.Rows[Convert.ToInt32(Session["QNO"])]["Question_Order"].ToString(), DT.Rows[Convert.ToInt32(Session["QNO"])]["Question"].ToString());
Session["Question_ID"] = DT.Rows[Convert.ToInt32(Session["QNO"])]["ID"].ToString();
if (DT.Rows[Convert.ToInt32(Session["QNO"])]["Type_Desc"].ToString() == "Multiple Choice")
{
Control uc = Page.LoadControl("UserControls/MultipleChoice.ascx");
PlaceHolder2.Controls.Add(uc);
}
else if (DT.Rows[Convert.ToInt32(Session["QNO"])]["Type_Desc"].ToString() == "Single Choice")
{
Control uc = Page.LoadControl("UserControls/SingleChoice.ascx");
PlaceHolder2.Controls.Add(uc);
}
else if (DT.Rows[Convert.ToInt32(Session["QNO"])]["Type_Desc"].ToString() == "Yes/No")
{
Control uc = Page.LoadControl("UserControls/YesOrNo.ascx");
PlaceHolder2.Controls.Add(uc);
}
else if (DT.Rows[Convert.ToInt32(Session["QNO"])]["Type_Desc"].ToString() == "Agree/Disagree")
{
Control uc = Page.LoadControl("UserControls/AgreeDisagree");
PlaceHolder2.Controls.Add(uc);
}
else if (DT.Rows[Convert.ToInt32(Session["QNO"])]["Type_Desc"].ToString() == "Rating")
{
Control uc = Page.LoadControl("UserControls/Rating.ascx");
PlaceHolder2.Controls.Add(uc);
}
else if (DT.Rows[Convert.ToInt32(Session["QNO"])]["Type_Desc"].ToString() == "Open Ended")
{
Control uc = Page.LoadControl("UserControls/OpenEnded.ascx");
PlaceHolder2.Controls.Add(uc);
}
}
}
现在,假设类型为“Open Ended”,它在 中显示一个文本框usercontrol
,我想访问此文本框并检索其中的文本,然后按一下按钮将其放入另一个文本框中,我创建了一个静态文本框该页面并调用它ViewTextBox
。这是我尝试过的:-
protected void Button1_Click(object sender, EventArgs e)
{
TextBox t = Controls[0].Controls[3].Controls[11].Controls[5].Controls[0].Controls[0] as TextBox;
ViewTextBox.Text = t.Text; //"Object reference not set to an instance of an object."
}
有任何想法吗?我通过页面上的控件挖掘了我的方式以在用户控件中找到文本框:-
Response.Write(Controls[0].Controls[3].Controls[11].Controls[5].Controls[0].Controls[0].ID);
并且 ID 作为我正在寻找的文本框出现。用户控件中的文本框称为“OpenEndedTextBox”