1

I am trying to populate a data table using the SQL datasource based upon parametrized inputs .The tricky thing is that the value of the parametrized input is available only in the code behind so I am forced to write the SQL datasource in the code behind page

How do I go about it ( I am using C# and ASP.Net 4.0)

The current code in the asp.net page to create the sql datasource connection is :

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:LicensingConnectionString %>" 
        SelectCommand="SELECT * FROM [commissions] where username=@username "></asp:SqlDataSource>

The value I want to use in @username is retrieved in the code behind by this code

IPrincipal p = HttpContext.Current.User;
        // p.Identity.Name : this is what we will use to call the stored procedure to get the data and populate it
        string username = p.Identity.Name;

Thanks !

1 Answer 1

7

You need to handle the OnSelecting event of the data source, and in there you can set the parameter's value.

In your page:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:LicensingConnectionString %>" 
        SelectCommand="SELECT * FROM [commissions] where username=@username"
        OnSelecting="SqlDataSource1_Selecting" >
    <SelectParameters>
        <asp:Parameter Name="username" Type="String" />
    </SelectParameters>
</asp:SqlDataSource>

In your codebehind:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
     e.Command.Parameters["@username"].Value = HttpContext.Current.User.Identity.Name;
}
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.