在下拉列表中显示所选值

时间:2015-06-26 23:16:11

标签: c# sql asp.net sql-server-2008 drop-down-menu

我有一个可以查看和更新​​记录的表单。正在从存储过程填充数据。除了我的下拉列表外,所有内容都很好。这是我的代码背后:

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>

我可以像我正在尝试的那样一步完成这一切,还是需要分两步完成?我的问题的后半部分是我还需要具有与用户对应的项目,默认情况下在下拉列表中选择。第二种方法填充下拉列表,但没有选择任何内容,因为它是一个单独的查询,因此与我在表单中查看的用户数据没有关联。

1 个答案:

答案 0 :(得分:0)

知道了。解决方案发布在下面以供参考......

代码背后:

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>