Skip to main content
 首页 » 编程设计

c#之ASP.NET Repeater之在 HeaderTemplate 中显示数据绑定(bind)

2024年02月20日12insus

我有一个转发器,我想在我的数据库中的 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> 

但我的页眉中没有显示任何内容。我听说您不能在 header 中使用数据绑定(bind)器,所以有人可以推荐如何执行此操作吗?

这是我的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(); 

请您参考如下方法:

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

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

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

public string TopicName { get; set; } 

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

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

边注

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

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

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