1

I am creating DIVs dynamically which will fetch data from my sql table(from each row) and will show it in DIVs. What problem I am facing is, it only shows the last row of my sql table in a div form Here is the 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>

and here is the cs code

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++;
                }
            }
         }
      }
1
  • Are you using ASP.NET WebForms? Commented Apr 20, 2016 at 11:09

2 Answers 2

2

Try using a Repeater, like this (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>

And supply a DataSource in the code behind on the server, and add '<%# Eval("ColumnName") %>' expressions in the markup where appropriate.

Sign up to request clarification or add additional context in comments.

Comments

0

The standard approach is to use a GridView:

https://msdn.microsoft.com/en-us/library/aa479342.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.