2009-06-17 50 views
0

大家好我正在一個小項目上,我在這個基礎上添加控件到一個基於SQL表格的問題,這張表會增加加班時間。我只是想分享這些代碼,看看是否有更好的方法,或者是否有專家可以參與進來,並讓我對未來的問題有所瞭解。下面是代碼:添加控件依賴於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); 

    } 

回答

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

如果控制或者使用或者促成的ViewState ,那麼你必須確保相同的控件按照相同的順序添加到ViewState中,並且每次回發。對象添加到ViewState的順序取決於控件樹中控件的順序。