2011-05-18 184 views
1

我想使用基于参数化输入的SQL数据源填充数据表。棘手的是,参数化输入的值仅在后面的代码,所以我被迫写在代码隐藏页的SQL数据源在C#代码中编写SQLdatasource以使用代码背后的代码

我如何去了解它(我使用C#和aSP.Net 4.0)

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

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     ConnectionString="<%$ ConnectionStrings:LicensingConnectionString %>" 
     SelectCommand="SELECT * FROM [commissions] where [email protected] "></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; 

谢谢!

回答

7

您需要处理数据源的OnSelecting事件,并且可以在其中设置参数的值。

在你的页面:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     ConnectionString="<%$ ConnectionStrings:LicensingConnectionString %>" 
     SelectCommand="SELECT * FROM [commissions] where [email protected]" 
     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; 
} 
+0

完全,精美的工作,非常感谢! – 2011-05-18 18:24:21