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>
5
  • QueryStringParameter: msdn.microsoft.com/en-us/library/… Commented Aug 12, 2013 at 20:58
  • 2
    This code is open to a SQL Injection attack - stackoverflow.com/questions/332365/… Commented Aug 12, 2013 at 21:01
  • i had to add this <SelectParameters> <asp:QueryStringParameter Name="ID" QueryStringField="Post_ID" Type="String" /> Commented Aug 12, 2013 at 21:01
  • Moe, if this is the solution, you can post it as an answer. Commented Aug 12, 2013 at 21:03
  • I updated my accepted answer to reflect your comment. Commented Aug 13, 2013 at 12:27

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Aww, Karl, don't give him code that keeps the injection attack in there!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.