【问题标题】:Dynamically creating DIVs from Database in ASP.NET在 ASP.NET 中从数据库动态创建 DIV
【发布时间】:2013-12-22 16:01:04
【问题描述】:

这是一个初学者的问题。我想从数据库 (MSSQL) 动态创建 div。例如,我想在条目下方显示 cmets。 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>

这将对所有 cmets 重复。而且我正在处理所有代码隐藏(没有评估)。我的 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 循环。但我现在不知道如何并且需要一个例子。

感谢您的帮助。

【问题讨论】:

  • 你用谷歌搜索过“repeater C# asp.net”吗?

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


【解决方案1】:

编辑:答案已完全修改。

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

在这两种解决方案中,我强烈建议在选择查询中专门命名您的字段,而不是使用星号来选择所有字段。如果表结构发生变化,使用 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>

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

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.

【讨论】:

  • 我真的很抱歉,但这与问题无关。我不是说你错了,而是你断章取意。
  • @danish,这个问题非常具体“我想从数据库动态创建 div”,我认为这是正确的。
  • OP 在这里看起来很困惑。他真的不需要多个div。他可以使用任何支持 IListSource 进行数据绑定的东西来执行此操作。我这里可能错了。
  • 我同意这是一种基本方法(我将添加一个说明它的基本方法)。实际上,我这样做是为了演示一些用于迭代 SqlDataReader 并用它“做事”的基本技术。
  • @DavidR 非常感谢你这篇精彩的文章。这正是我正在寻找的。我用的是第二种方式,效果不错。
【解决方案2】:

按照 Phill Sandler 的建议,您可以使用中继器。查看以下链接以获取完整代码。

Create Dynamic Control using Repeater and List

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    相关资源
    最近更新 更多