2

Is it possible to use a field name as a select parameter in an SQLDataSource?

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:DbConnection %>" 
    ProviderName="<%$ ConnectionStrings:DbConnection.ProviderName %>"      
SelectCommand="select * from sometable where @FieldKey = @FieldValue">
<SelectParameters>
    <asp:Parameter Name="FieldKey" Type="String" />
    <asp:Parameter Name="FieldValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
2
  • What are you trying to accomplish? Commented May 31, 2012 at 1:57
  • To be able to change the where condition based on a supplied field name Commented May 31, 2012 at 2:56

3 Answers 3

1

Here is my hack(workaround) most time

protected void page_load(...)
{
   SqlDataSource1.SelectParameters["FieldKey"] = field;
   SqlDataSource1.SelectParameters["FieldName"] = name;
}

OR create two hidden fields, assign the values to those fields and then use

<asp:ControlParameter />

That is another hack

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

Comments

1

OPTION 1

If FieldKey and FieldName are taking from code behind I think you can easily set command as below.

SqlDataSource1.SelectCommand = string.Format("select * from sometable where {0} = {1}",fieldKey ,fieldValue)

please validate input fields for SQL injection attacks.

OPTION 2

Create stored procedure to accept two parameters key and value, you need to build SQL query from those parameters and execute inside stored procedure.

Then you can call it from datasource.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:DbConnection %>" 
    ProviderName="<%$ ConnectionStrings:DbConnection.ProviderName %>"      
    SelectCommand="StoredProcedureName"
    SelectCommandType="StoredProcedure">
<SelectParameters>
    <asp:Parameter Name="FieldKey" Type="String" />
    <asp:Parameter Name="FieldValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>

2 Comments

That is the way I ended up going, however, I would rather a solution straight from the .aspx page.
@jax add another alternative way
0

If what you mean is using values from a control [like textbox, dropdown] then here is something

<SelectParameters>
    <asp:ControlParameter ControlID="FieldKey" PropertyName="Text"
         Type="String" />
    <asp:ControlParameter ControlID="FieldName" PropertyName="Text"
         Type="String" />
</SelectParameters>

Assuming the values are stored in textboxes

1 Comment

No, the SQL is inside a class that extends UserControl, the property is in the code behind of this class

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.