大家好我正在开发一个小项目,我正在根据SQL表格向页面添加控件,这个表格会超时。我只是想分享代码,看看是否有更好的方法,或者是否有任何专家可以参与其中并给我任何关于未来问题的见解。这是代码:
protected void Page_Load(object sender, EventArgs e)
{
try
{
SqlParameter[] paramz = new SqlParameter[1];
paramz[0] = new SqlParameter("@c_id", 1);
dt = SqlHelper.ExecuteDataTable(ConfigurationManager.ConnectionStrings["sql"].ToString(), CommandType.StoredProcedure, "get_Questions", paramz);
clinicName.Text = "<b>" + dt.Rows[0]["Clinic Name"].ToString();
for(int row = 0; row <= dt.Rows.Count; row++)
{
if (row == dt.Rows.Count) //if we're on the last question put a break for spacing(this could be fixed with styling)
{
Literal alit = new Literal();
alit.Text = "<br/>";
questionsPanel.Controls.Add(alit);
}
else
{
addQuestion(dt.Rows[row], row);
}
}
}
catch (Exception err)
{
Response.Write(err.Message);
}
}
private void addQuestion(DataRow row, int i)
{
Label lbl = new Label();
lbl.Text = row["question"].ToString();
questionsPanel.Controls.Add(lbl);
Literal lit = new Literal();
lit.Text = "<br/>";
questionsPanel.Controls.Add(lit);
TextBox txt = new TextBox();
txt.ID = "txt" + i.ToString();
questionsPanel.Controls.Add(txt);
Literal lit2 = new Literal();
lit2.Text = "<br/>";
questionsPanel.Controls.Add(lit2);
}
答案 0 :(得分:3)
使用Repeater控件:
ASPX代码:
<asp:Repeater id="repData" runat="server">
<ItemTemplate>
<asp:Label id="lblQuestion" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "question") %>' />
<br />
<asp:TextBox id="lblAnswer" runat="server" />
</ItemTemplate>
<FooterTemplate>
<br />
</FooterTemplate>
</asp:Repeater>
代码背后:
// Populate repeater
SqlParameter[] paramz = new SqlParameter[1];
paramz[0] = new SqlParameter("@c_id", 1);
dt = SqlHelper.ExecuteDataTable(ConfigurationManager.ConnectionStrings["sql"].ToString(), CommandType.StoredProcedure, "get_Questions", paramz);
repData.DataSource = dt;
repData.DataBind();
答案 1 :(得分:1)
如果控件使用或贡献给ViewState,那么必须确保在每个回发上以相同的顺序将相同的控件添加到ViewState。将对象添加到ViewState的顺序取决于控制树中控件的顺序。