在asp.net中创建动态DIV#

时间:2016-04-20 11:02:24

标签: c# sql asp.net webforms

我正在动态创建DIV,它将从我的sql表(从每一行)中获取数据,并将在DIV中显示它。我面临的问题是,它只以div格式显示我的sql表的最后一行 这是html

<div ID = "containerDiv" class="container" runat = "server">
  <div ID = "columnDiv" class="col-md-3 col-sm-4" runat = "server">
     <div ID = "textDiv" class="text" runat="server">
     </div>
   </div>
</div>

这是cs代码

static int count = 0;
    protected void Page_Load(object sender, EventArgs e)
    {

        string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM tblProducts"))
            {
                cmd.Connection = con;
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    columnDiv.ID = "columnDiv" + count;
                    textDiv.ID = "textDiv" + count;
                    string name = rdr["prod_name"].ToString();
                    string price = rdr["prod_price"].ToString();


                    textDiv.InnerHtml = name + "   " + price;

                    columnDiv.Controls.Add(textDiv);

                    containerDiv.Controls.Add(columnDiv);
                    count++;
                }
            }
         }
      }

2 个答案:

答案 0 :(得分:2)

尝试使用Repeater,如下所示(here's the MSDN):

<asp:Repeater ID="Repeater1" runat="server">
      <ItemTemplate>
          <div ID="containerDiv" class="container" runat = "server">
              <div ID="columnDiv" class="col-md-3 col-sm-4" runat = "server">
                  <div ID="textDiv" class="text" runat="server">
                  </div>
              </div>
          </div>
      </ItemTemplate>
</asp:Repeater>

在服务器后面的代码中提供DataSource,并在适当的位置在标记中添加'<%# Eval("ColumnName") %>'个表达式。

答案 1 :(得分:0)