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