简体   繁体   English

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

[英]Writing a SQLdatasource in code behind in C# to use a code behind value

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 我正在尝试使用基于参数化输入的SQL数据源填充数据表。棘手的事情是,参数化输入的值仅在后面的代码中可用,因此我被迫在页面后面的代码中编写SQL数据源

How do I go about it ( I am using C# and ASP.Net 4.0) 我该怎么做(我正在使用C#和ASP.Net 4.0)

The current code in the asp.net page to create the sql datasource connection is : asp.net页中用于创建sql数据源连接的当前代码为:

<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 我要在@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;

Thanks ! 谢谢 !

You need to handle the OnSelecting event of the data source, and in there you can set the parameter's value. 您需要处理数据源的OnSelecting事件,并可以在其中设置参数的值。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM