ASP.Net中的动态查询(SQLDataSource中的WHERE子句)

时间:2012-05-10 18:54:27

标签: asp.net sql vb.net sqldatasource

我正在尝试遍历一个数组(两个值)并在循环内的查询中使用这两个值。请参阅下面的代码。现在我的代码不起作用。我正在尝试动态填充SQLDataSource的“SelectParameters”标记中的“appType”参数,但这不起作用。

有什么建议吗?

<%

    Dim appTypes() As String = {"Extranet", "Internet"}

    For Each appType As String In appTypes

%>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ProviderName = "<%$ ConnectionStrings:CMS.ProviderName %>"
    SelectCommand = "SELECT Applications.Name as AppName, Applications.Abbr as AppAbbr, Types.Name as TypeName, Managers.LastName as LastName, Managers.FirstName As FirstName, Managers.EDKeyEmpID as EDKeyID
        FROM Types INNER JOIN (Managers INNER JOIN Applications ON Managers.ID=Applications.Manager) ON Types.ID=Applications.Type
        WHERE (Types.Name = @appType)
           ORDER BY Types.Name, Applications.Name;"
    ConnectionString="<%$ ConnectionStrings:CMS %>">
    <SelectParameters>
        <asp:Parameter DefaultValue="<%=appType%>" Name="appType"  Type="String" />
    </SelectParameters>   
</asp:SqlDataSource>

<asp:Repeater ID="Repeater1" DataSourceID="SqlDataSource1" runat="server">
    <ItemTemplate>
        <%#Eval("AppName")%> (<%=appType%>)
    </ItemTemplate>
</asp:Repeater>


<% Next %>

1 个答案:

答案 0 :(得分:2)

修改您的SqlDataSource以拥有OnSelecting成员:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" OnSelecting="OnSelecting"

将SelectParameters重置为正常状态:

<SelectParameters>
    <asp:Parameter Name="appType" Type="String" />
</SelectParameters>

在代码隐藏中定义此方法。根据需要实现逻辑。在这里,我显示了Repeater的虚拟值。由你决定实际来自何处/何处(SelectedItem或类似的东西)。

Protected Sub OnSelecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
    e.Command.Parameters("@appType").Value = Repeater1.SomeValue
End Sub