繁体   English   中英

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

[英]Dynamically creating DIVs from Database in ASP.NET

这是一个初学者的问题。 我想从数据库( MSSQL )动态创建div。 例如,我想在条目下面显示评论。 Comment表通过EntryIDEntry表连接。 我的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循环。 但我不知道如何并且需要一个例子。

感谢帮助。

编辑:答案完全修订。

在您的问题中,您需要一种方法来循环并在每次循环迭代中添加注释。 您可以这样做,但使用内置的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应用程序应该使用更好的解决方案。 更好的解决方案是使用数据绑定 互联网上有很多文章和教程,所以如果这是一个新想法,你可以做一些教程来学习数据绑定的细节。

要使用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.

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

使用Repeater和List创建动态控制

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM