Dynamic query in ASP.Net (WHERE clause in SQLDataSource)

a 夏天 提交于 2019-12-11 15:41:04

问题


I'm currently trying to loop through an array (two values) and use both values in a query inside the loop. Please see code below. Right now my code doesn't work. I'm trying to populate dynamically the "appType" parameter within the "SelectParameters" tags of the SQLDataSource, but this won't work.

Any suggestion?

<%

    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:


Modify your SqlDataSource to have an OnSelecting member:

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

Reset your SelectParameters back to normal:

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

Define this method in your code-behind. Implement the logic as required. Here I've shown a dummy value from your Repeater. It'll be up to you to determine how/where that actually comes from (SelectedItem or something similar).

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


来源:https://stackoverflow.com/questions/10540470/dynamic-query-in-asp-net-where-clause-in-sqldatasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!