在C#中的代码中编写SQLdatasource以使用值后面的代码

Mer*_*ngh 1 c# asp.net sqldatasource entity-framework-4

我正在尝试使用基于参数化输入的SQL数据源填充数据表.棘手的是,参数化输入的值仅在后面的代码中可用,所以我被迫在页面代码中编写SQL数据源

我该怎么做(我使用的是C#和ASP.Net 4.0)

asp.net页面中创建sql数据源连接的当前代码是:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:LicensingConnectionString %>" 
        SelectCommand="SELECT * FROM [commissions] where username=@username "></asp:SqlDataSource>
Run Code Online (Sandbox Code Playgroud)

我希望在@username中使用的值在此代码后面的代码中检索

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;
Run Code Online (Sandbox Code Playgroud)

谢谢 !

pat*_*ech 7

您需要处理数据源的OnSelecting事件,并在那里设置参数的值.

在您的页面中:

<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>
Run Code Online (Sandbox Code Playgroud)

在你的代码隐藏中:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
     e.Command.Parameters["@username"].Value = HttpContext.Current.User.Identity.Name;
}
Run Code Online (Sandbox Code Playgroud)