问题描述:

I have a sqlDataSource in which I use select parameter as below :

<asp:sqlDataSource ID="EmployeeDetailsSqlDataSource"

SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID"

ConnectionString="<%$ ConnectionStrings:NorthwindConnection %>" RunAt="server">

<SelectParameters>

<asp:Parameter Name="EmpID" Type="Int32" DefaultValue="<%#userid%>" />

</SelectParameters>

</asp:sqlDataSource>

In my backend code, I have assigned a value to userId and also written this.DataBind();

The data-binding doesn't work. Does anyone know a solution to this ?

网友答案:

One approach is to just set the value with the userid variable in the code behind Page_Load event or after you bind your variable.

 //set SqlDataSource parameters value with empID as your variable
EmployeeDetailsSqlDataSource.SelectParameters.Add("@EmpID", userID);

Asp:

 <asp:sqlDataSource ID="EmployeeDetailsSqlDataSource" 
          SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID"
          RunAt="server"> 
<SelectParameters>
    <asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />
      </SelectParameters>
        </asp:sqlDataSource>

Another option is to set the value from code in the selecting event which occurs before a data retrieval.

SqlDataSource.Selecting Event

Here is a link to a more complete example Full Example

<asp:sqlDataSource ID="EmployeeDetailsSqlDataSource" 
          SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = @EmpID"
          RunAt="server" OnSelecting=OnSelectingHandler">
 <SelectParameters>
<asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />
 </SelectParameters>
 </asp:sqlDataSource>

Code behind:

Public void OnSelectingHandler(object sender, SqlDataSourceSelectingEventArgs e)
{

e.Command.Parameters[0].Value=userID;

}
相关阅读:
Top