0

I am trying to use sql command in ASPX file to capture a querysring value but having some syntax issue. Everything works fine but when i try to filter it by querystring then i get the syntax issue. How can i filter it my query using the querystring? Here is my code:

<asp:SqlDataSource ID="DD_AI_DS" runat="server" 
              ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" 
              SelectCommand="SELECT DISTINCT [MyField] FROM [MyTable] where ID = '"+request.querystring[ID]+"' order by ID asc" >
          </asp:SqlDataSource>
moe
  • 5,149
  • 38
  • 130
  • 197

2 Answers2

4

Try this instead:

<asp:SqlDataSource ID="DD_AI_DS" runat="server" 
   ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" 
   SelectCommand="SELECT DISTINCT [MyField] FROM [MyTable] where ID = @ID order by ID asc" >
   <SelectParameters>
    <asp:QueryStringParameter Name="ID" QueryStringField="Post_ID" Type="String" />
   </SelectParameters>
</asp:SqlDataSource>

As an aside, if the code you had written had actually worked then it would have created a security hole in your website by allowing sql injection. I would read up on this topic so you don't accidentally make your websites open to hackers.

rtpHarry
  • 13,019
  • 4
  • 43
  • 64
0

You can also set the SqlDataSource properties in code-behind, like this:

DD_AI_DS.SelectCommand = "SELECT DISTINCT [MyField] FROM [MyTable] where ID = '"+ Request.QueryString[ID] + "' order by ID asc";
DD_AI_DS.Select(DataSourceSelectArguments.Empty);

Note: This gives you the support of IntelliSense in Visual Studio and catching some issues at compile-time.

Karl Anderson
  • 34,606
  • 12
  • 65
  • 80