【问题标题】:adding controls dependent on sql table?添加依赖于sql表的控件?
【发布时间】:2010-11-03 12:37:22
【问题描述】:

大家好,我正在做一个小项目,我正在根据 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);

    }

【问题讨论】:

    标签: c# .net asp.net dynamic


    【解决方案1】:

    使用中继器控件:

    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();
    

    【讨论】:

      【解决方案2】:

      如果控件使用或贡献给 ViewState,那么您必须确保在每次回发时以相同的顺序将相同的控件添加到 ViewState。对象添加到 ViewState 的顺序取决于控件树中控件的顺序。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-15
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        • 2021-11-16
        相关资源
        最近更新 更多