在创建一个调查页面时,此页面从数据库中拉出以显示基于它们类型的问题。对于每种类型,我创建了一个用户控件。在Page_Load
,我把在这样的占位符的用户控件: - (侠诺是一个会话我设置为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”
你能告诉我为什么我得到“对象引用未设置为对象的实例”。那条线上的错误? –
@ BasharAl-Khalili最有可能您试图找到的控件不存在于您试图从中获取的索引处。这就是为什么我建议您创建该方法,以便您不必遍历这些索引。 – yogi