【问题标题】:ASP.NET Repeater - Display Databound in HeaderTemplateASP.NET 中继器 - 在 HeaderTemplate 中显示数据绑定
【发布时间】:2012-05-21 04:32:15
【问题描述】:

我有一个中继器,我想在我的数据库中的 HeaderTemplate 中添加一个标题

这是我目前的代码

<asp:Repeater ID="topicView" runat="server">
    <HeaderTemplate>
        <tr>
            <td>
                <h1><%#DataBinder.Eval(Container.DataItem, "TopicName")%></h1>
            </td>
        </tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>
                <%#DataBinder.Eval(Container.DataItem, "PostBody")%>
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        <tr>
            <td>
            </td>
        </tr>
    </FooterTemplate>
</asp:Repeater>

但我的标题中没有显示任何内容。我听说你不能在标题中使用 databinder,所以有人可以推荐如何做到这一点吗?

这是我的 CS 代码

    string topic = Request.QueryString["topicid"].ToString();

    // Define the select statement.
    // All information is needed
    string selectSQL = "SELECT * FROM PostView WHERE TopicID ='" + topic + "'";

    // Define the ADO.NET Objects
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand(selectSQL, con);
    con.Open();
    SqlDataReader postView = cmd.ExecuteReader();
    topicView.DataSource = postView;
    topicView.DataBind();

【问题讨论】:

    标签: c# asp.net repeater


    【解决方案1】:

    您不需要绑定到数据源,只需绑定到页面的一个简单属性即可。在 HeaderTemplate 中使用它:

    <h1><%# TopicName %></h1>
    

    然后将 TopicName 作为公共属性添加到代码隐藏中。

    public string TopicName { get; set; }
    

    然后在运行查询时设置它:

    TopicName = Request.QueryString["topicid"].ToString();
    

    旁注

    不确定您是否知道,但您应该小心 SQL 注入。与其将查询字符串直接注入 SQL 查询,不如使用

    string selectSQL = "SELECT * FROM PostView WHERE TopicID ='{0}';
    

    然后将主题作为参数添加到您的 SqlCommand 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 2015-09-20
      相关资源
      最近更新 更多