aggiungere controlli dipendenti dalla tabella sql?
Domanda
Ciao, sto lavorando a un piccolo progetto in cui sto aggiungendo controlli a una pagina basata su una tabella di domande SQL, questa tabella aumenterà di tanto in tanto. Volevo solo condividere il codice e vedere se c'era un modo migliore o se qualcuno degli esperti poteva intervenire e darmi qualche idea su problemi futuri. Ecco il codice:
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);
}
Soluzione
Usa un controllo Repeater:
Codice 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>
Codice dietro:
// 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();
Altri suggerimenti
Se i controlli utilizzano o contribuiscono a ViewState, è necessario assicurarsi che gli stessi controlli vengano aggiunti a ViewState nello stesso ordine, su ogni post. L'ordine in cui gli oggetti vengono aggiunti a ViewState dipende dall'ordine dei controlli nella struttura dei controlli.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow