ASP.net嵌套中继器拼图:基于来自外部中继器的数据的内部SQL查询

时间:2013-08-01 21:08:13

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

好吧,我担心标题可能会令人困惑,所以让我试着用我的例子来描述这个。假设我有一个包含2列的SQL Server表,一个Text列和一个Category列。

在此代码中的嵌套转发器中,我想显示SQL Server表中共享相同类别的所有数据行。 然而,我需要了解的类别本身来自上述转发器。

<asp:Repeater ID="RepeaterOuter" runat="server" DataSourceID="SqlDataSourceGrantCategories">
<ItemTemplate>

<%# Eval("Category") %> //Here I can access Category just fine.

    <asp:SqlDataSource ID="SqlDataSourceGrantInfo" runat="server" ConnectionString="<%$ ConnectionStrings:CMSConnectionString %>"
    SelectCommand='<%# "SELECT * FROM [cfhudson_grants] WHERE Category =" + Eval("Category") %>'  /> //Here I cannot access the current Category coming from the outer repeater, so I cannot make a query based on Category :(

    <asp:Repeater ID="RepeaterInner" runat="server" DataSourceID="SqlDataSourceGrantInfo">
        <ItemTemplate>
        <%# Eval("Text") %> //Text from the current data row.
        </ItemTemplate>
    </asp:Repeater> //This repeater should list all rows of the current category.

</div>    
</ItemTemplate>
</asp:Repeater> //This repeater brings the next Category to the nested repeater.

我无法从外部转发器获取该类别数据,在查询内部使用另一个SQL Server表,该表中还有一个名为Category的列。我想知道是否有人可以帮助我,或者是否有办法使用SQL查询进行排序。

简单来说,我只想用Category对这些中继器进行数据排序。所以让他们创建类似:Category1,Cat1Data1,Cat1Data2,Category2,Cat2Data1,Cat2Data2等等。

我很乐意提供有关此问题的更多信息,因为它阻止了我正在为孩子们工作的非营利性网站上的最终修改。这个问题已经持续了一个多星期了。我是ASP.net,C#和SQL Server的新手。希望其他人遇到类似的事情。它看起来并不太牵强,似乎很常见,但网上很少有关于它的文档。

2 个答案:

答案 0 :(得分:2)

关键是向ItemDataBound添加一个事件处理程序,它将数据绑定到每行的嵌套转发器,如下所示: http://www.codeproject.com/Articles/6140/A-quick-guide-to-using-nested-repeaters-in-ASP-NET

答案 1 :(得分:1)

将您的SelectCommand更改为:

SelectCommand='<%# getQuery(Eval("Category")) %>'

所以SqlDataSource现在看起来像这样:

<asp:SqlDataSource ID="SqlDataSourceGrantInfo" runat="server" ConnectionString="<%$ ConnectionStrings:CMSConnectionString %>" SelectCommand='<%# getQuery(Eval("Category")) %>' />

在您的代码中添加以下函数:

public string getQuery(object cat)
{ 
    return "SELECT * FROM [cfhudson_grants] WHERE Category ='" + cat.ToString() + "'";
}

应该有用。

相关问题