【问题标题】:Writing a SQLdatasource in code behind in C# to use a code behind value在 C# 中的代码后面编写 SQLdatasource 以使用代码后面的值
【发布时间】:2011-08-28 06:50:21
【问题描述】:

我正在尝试使用基于参数化输入的 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>

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

谢谢!

【问题讨论】:

    标签: c# asp.net entity-framework-4 sqldatasource


    【解决方案1】:

    您需要处理数据源的 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>
    

    在您的代码隐藏中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      相关资源
      最近更新 更多