Question

It is a beginner question. I want to create divs dynamically from database (MSSQL). For example, i want to show comments below an entry. The Comment table connected with Entry table by EntryID. My aspx code is like:

<div class="commentBody" runat="server">
      <asp:Label ID="commentSender" runat="server" Text=""></asp:Label>
      <asp:Label ID="commentDate" runat="server" Text=""></asp:Label>
      <asp:Label ID="commentText" runat="server" Text=""></asp:Label>
</div>

This will be repeat for all comments. And I am working all codebehind (without evals). My c# code:

protected void YorumlariGetir()
{   
    string selectComments = "SELECT * FROM Comment WHERE Comment.EntryID = @EntryID";

    SqlConnection conn = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand(selectComments, conn);

    cmd.Parameters.AddWithValue("@EntryID", Session["EntryID"].ToString());

    try
    {
        conn.Open();
        // HERE I WANT TO CALL A LOOP FOR COMMENTS

    }
    catch (Exception ex)
    {
        Response.Write("Hata: " + ex.Message);
    }
    finally
    {
        conn.Close();
    }
}

I can use repeaters or foreach loop. But i don't know how and need an example at this point.

Thanks for help.

Was it helpful?

Solution

EDIT: Answer fully revised.

In your question you ask for a way to do looping and add comments on each loop iteration. You can do this but there are far better ways using built in ASP.NET controls. I will first show you a basic example that simply iterates the SqlDataReader object and manually creates HTML. Then I will show a much better solution. I do not recommend the first option if you are able to implement the second one.

On both solutions, I strongly suggest to specifically name your fields in the select query instead of using an asterisk to select all fields. Using SELECT * can cause issues if the table structure changes. Also, you may be selecting data columns you do not need which wastes resources.

First, here is very simple example using the SqlDataReader class. This will work, but remember there is a better way.

    try
    {
        conn.Open();
        // HERE I WANT TO CALL A LOOP FOR COMMENTS
        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            // create the div to wrap around the comment
            HtmlGenericControl div = new HtmlGenericControl("div");
            div.Attributes.Add("style", "commentBody");

            // create three labels and add them to the div
            // 1,2,3 are the ordinal positions of the column names, this may need corrected since I have no idea what your table looks like.
            div.Controls.Add(new Label() { Text = reader.GetString(1) });
            div.Controls.Add(new Label() { Text = reader.GetString(2) });
            div.Controls.Add(new Label() { Text = reader.GetString(3) });

            // add the div to the page somehow, these can be added to any HTML control that can act as a container. I would suggest a plain old div.
            MyMainDiv.Controls.Add(div);

        }
    } 

Now, the above method will work, but it is a clumsy, old-fashioned, way to handle displaying data. Modern .NET applications should use better solutions where available. A better solution would be to use Data Binding. There are many articles and tutorials on this across the Internet, so if this is a new idea, you can do some tutorials to learn the finer points of Data Binding.

To use the Repeater class, first add a Repeater control to your ASPX page:

<asp:Repeater id="Repeater1" runat="server">
    <ItemTemplate>
        <div class="commentBody">
            <span class="commentSender"><%# DataBinder.Eval(Container.DataItem,"aucommentSenderid") %></span>
            <span class="commentDate"><%# DataBinder.Eval(Container.DataItem,"aucommentDateid") %></span>
            <span class="commentText"><%# DataBinder.Eval(Container.DataItem,"aucommentTextid") %></span>
        </div>
    </ItemTemplate>
</asp:Repeater>

Next, add some code-behind to create a datasource and attach this to the Repeater control:

SqlDataAdapter da = new SqlDataAdapter(cmd);      // use your existing SqlCommand here (don't use select *)
DataSet ds = new DataSet();                       // create a DataSet object to hold you table(s)... this can contain more than 1 table
da.Fill(ds, "Comment");                           // fill this dataset with everything from the Comment Table
Repeater1.DataSource = ds.Tables["Comment"];      // attach the data table to the control
Repeater1.DataBind();                             // This causes the HTML to be automatically rendered when the page loads.

OTHER TIPS

As Phill Sandler suggested you can used repeater.Check out the following link for complete code.

Create Dynamic Control using Repeater and List

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top