c# - 在 C# 的代码隐藏中编写 SQLdatasource 以使用代码隐藏值

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

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

谢谢!

最佳答案

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

关于c# - 在 C# 的代码隐藏中编写 SQLdatasource 以使用代码隐藏值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6048983/

相关文章:

c# - 在 MVC 4 脚本部分初始化 jQuery DataTable 时隐藏表数据的最佳方法是什么

c# - Entity Framework LINQ 投影到自定义类型导致数据丢失

c# - 通过代码使 Texture2D 在 Unity 中可读

asp.net - 如何更改中继器中的列(数据集)值名称

c# - 从服务器端访问网络存储 - 可能吗?

asp.net - 如何为 Azure 应用程序创建可搜索的文档存储库?

c# - 使用 WEB API 的 EntityFramework,更新所有属性

entity-framework-4 - Linq 中的 DateTime 操作到实体查询

c# - c# 客户端和 java 服务器之间的安全通信

c# - 获取输出差异图中的节点名称而不是它们的索引