您没有说明当前代码会发生什么,但我敢打赌,当您选择一名员工时,页面会重新加载,并且您会获得数据库中所有员工的列表,对吧?
如果确实如此,原因是因为同一个 SqlDataSource 绑定到 DropDownList 和 GridView,并且 SqlDataSource 的 Select 命令检索所有员工 - 没有 WHERE 标准来选择所需的员工。
我将使用 2 个 SqlDataSources - 一个用于 DropDownList,另一个用于 GridView。第二个 SqlDataSource 将有一个 Select 命令,用于根据 DropDownList 中的选择获取所需员工的信息。
您可以修改 SqlDataSource2 的 SelectCommand 以仅返回全名和 EmployeeID 字段,因为 DropDownList 不需要其余字段:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:DropDownList ID="DropDownListEmployee" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="SelectionHasChanged"
DataSourceID="SqlDataSource2" DataTextField="Fullname"
DataValueField="Employee_ID" AppendDataBoundItems="true"
Width="214px">
<asp:ListItem>Select</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT F_Name + ' ' + L_Name AS Fullname, Employee_ID FROM Employee"></asp:SqlDataSource>
在第二个 SqlDataSource 中,您需要将参数 (EmployeeID) 添加到 SelectParameters 集合中,如下所示,并更新 SelectCommand 以获取该参数。
<asp:SqlDataSource ID="gvDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT Employee.F_Name + ' ' + Employee.L_Name AS Fullname, Employee.Primary_Address, Employee.Primary_Phone, Employee.E_mail, Credentials.Degree, Credentials.Years_Experience, Credentials.Certifications, Credentials.Positions, Employee.Employee_ID FROM Employee INNER JOIN Credentials ON Employee.Employee_ID = Credentials.Employee_ID WHERE Employee.EmployeeID = IsNull(@EmployeeID, EmployeeID)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownListID"
ConvertEmptyStringToNull="true" Name="EmployeeID"
PropertyName="SelectedValue" />
</SelectParameters>
然后将此 SqlDataSource 分配给 GridView 而不是第一个。
请注意,SqlDataSource 不会对提交到参数中的值进行验证 - 这可能会构成安全威胁。
SqlDataSource.Select 方法
SqlDataSource.SelectParameters 属性