在ASP.NET中从数据库动态创建DIV

时间:2013-12-22 16:01:05

标签: c# asp.net sql sql-server sqldatareader

这是一个初学者的问题。我想从数据库动态创建div( MSSQL )。例如,我想在条目下面显示评论。 条目表格通过条目ID 条目表格相关联。我的aspx代码就像:

<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>

对于所有评论,这将重复。我正在处理所有代码隐藏(没有逃避)。我的c#代码:

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

我可以使用中继器或foreach循环。但我不知道如何并且需要一个例子。

感谢您的帮助。

2 个答案:

答案 0 :(得分:7)

编辑:答案完全修订。

在你的问题中,你要求一种方法来循环并在每次循环迭代中添加注释。您可以这样做,但使用内置的ASP.NET控件有更好的方法。我将首先向您展示一个简单的迭代SqlDataReader对象并手动创建HTML的基本示例。然后我会展示一个更好的解决方案。如果您能够实现第二个选项,我不建议使用第一个选项。

在这两个解决方案中,我强烈建议您在select查询中专门命名字段,而不是使用星号来选择所有字段。如果表结构发生更改,则使用SELECT *会导致问题。此外,您可能正在选择不需要的数据列,这会浪费资源。

首先,这是使用SqlDataReader类的非常简单的示例。这会有效,但请记住有更好的方法。

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

        }
    } 

现在,上述方法将起作用,但它是处理显示数据的一种笨拙,过时的方式。现代.NET应用程序应该使用更好的解决方案。更好的解决方案是使用Data Binding。互联网上有很多这方面的文章和教程,所以如果这是一个新想法,你可以做一些教程来学习数据绑定的细节。

要使用Repeater类,首先将Repeater控件添加到ASPX页面:

<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>

接下来,添加一些代码隐藏以创建数据源并将其附加到Repeater控件:

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.

答案 1 :(得分:0)

正如Phill Sandler建议您可以使用repeater。请查看以下链接以获取完整代码。

Create Dynamic Control using Repeater and List