1

I am trying to pass a variable to a SelectCommand in SqlDataSource. I have this MyIdVal that need to be passed.

Here is the code :

<form id="form1" runat="server">

<div>
<%=MyIdVal%>
</div>
<asp:GridView ID="GridView1" runat="server" DataSourceID="myIdDataSource">
</asp:GridView>
<asp:SqlDataSource runat="server" ID="myIdDataSource" 
    ConnectionString="<%$  ConnectionStrings:myCipConnection  %>" 
    ProviderName="<%$ ConnectionStrings:myCipConnection.ProviderName %>"
    SelectCommand="SELECT * FROM books WHERE id = @MyIdVal" >   

    </asp:SqlDataSource>

</form>

The code works fine if I hardcode the id, so how this works?

2
  • try SelectCommand="SELECT * FROM books WHERE id = <%= MyIdVal%>" Commented May 22, 2012 at 15:44
  • it gives me this error now Conversion failed when converting the varchar value '<%=MyIdVal %>' to data type int. Commented May 22, 2012 at 15:53

1 Answer 1

3

Here's two ways to do it.

  1. Bind the Parameter value to a control

    <selectparameters>
        <asp:controlparameter 
                name="MyIdVal" 
                controlid="DropDownListBooks" 
                propertyname="SelectedValue"/>
    </selectparameters>
    

2 . Use the SqlDataSource.Selecting Event

protected void myIdDataSource_Selecting
    (object sender, ObjectDataSourceSelectingEventArgs e)
{
    e.InputParameters["MyIdVale"] = MyIdVal;
}
Sign up to request clarification or add additional context in comments.

Comments

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.