在下拉菜单中显示选定值
本文关键字:显示 下拉菜单 | 更新日期: 2023-09-27 18:00:14
我有一个可以查看和更新记录的表单。数据是从存储过程中填充的。除了我的下拉列表外,所有内容都很好。这是我的代码背后:
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
EmployeeIdTextBox.Text = sdr["EmployeeID"].ToString();
EmployeeNameTextBox.Text = sdr["EmployeeName"].ToString();
DepartmentDropDown.DataTextField = sdr["Department"].ToString();
DepartmentDropDown.DataValueField = sdr["Department"].ToString();
DepartmentDropDown.DataBind();
}
}
这是我的aspx:
<div>
EmployeeID:
<asp:TextBox ID="EmployeeIdTextBox" runat="server" CssClass="textBoxWidth" ReadOnly="True"></asp:TextBox>
</div>
<div>
EmployeeName:
<asp:TextBox ID="EmployeeNameTextBox" runat="server" CssClass="textBoxWidth" ReadOnly="True"></asp:TextBox>
</div>
<div>
Department:
<asp:DropDownList ID="DepartmentDropDown" runat="server" CssClass="textBoxWidth"></asp:DropDownList>
</div>
然而,如果我像下面这样更改aspx,我可以在下拉列表中获得值,尽管我更喜欢在后端完成这一切,因为我有比下面显示的更多的字段。
<asp:DropDownList ID="DepartmentDropDown" runat="server" CssClass="textBoxWidth"
DataSourceID="SqlDS1" DataTextField="Department"
DataValueField="Department" AutoPostBack="True">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDS1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT Department FROM Employees">
</asp:SqlDataSource>
我能像我想做的那样一步到位吗?还是需要分两步到位?我问题的后半部分是,我还需要在下拉列表中默认选择与用户相对应的项目。第二种方法填充下拉列表,但没有选择任何内容,因为它是一个单独的查询,因此与我在表单中查看的用户数据没有关联。
明白了。下面发布了解决方案以供参考。。。
代码背后:
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
EmployeeIdTextBox.Text = sdr["EmployeeID"].ToString();
EmployeeNameTextBox.Text = sdr["EmployeeName"].ToString();
DepartmentDropDown.DataBind();
DepartmentDropDown.Items.FindByValue(sdr["Department"].ToString()).Selected = true;
}
}
ASPX:
<asp:DropDownList ID="DepartmentDropDown" runat="server" CssClass="textBoxWidth"
DataSourceID="SqlDS1" DataTextField="Department"
DataValueField="Department" AutoPostBack="True">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDS1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT Department FROM Employees">
</asp:SqlDataSource>